一、題目
定義棧的資料結構,請在該型別中實現乙個能夠得到棧的最小元素的min函式。在該棧中,呼叫min、push及pop的時間複雜度都是o(1)。
二、關鍵
1.新增輔助棧,每次新增乙個元素,就往輔助棧中新增當前最小的那個元素。
三、解釋
四、**
#pragma once
#include #include template class stackwithmin
virtual ~stackwithmin() {}
t& top();
const t& top() const;
void push(const t& value);
void pop();
const t& min() const;
bool empty() const;
size_t size() const;
private:
std::stackm_data; // 資料棧,存放棧的所有元素
std::stackm_min; // 輔助棧,存放棧的最小元素
};template void stackwithmin::push(const t& value)
template void stackwithmin::pop()
template const t& stackwithmin::min() const
template t& stackwithmin::top()
template const t& stackwithmin::top() const
template bool stackwithmin::empty() const
template size_t stackwithmin::size() const
#include #include "stackwithmin.h"
void test(const char* testname, const stackwithmin& stack, int expected)
int main(int argc, char* argv)
面試題30 包含min函式的棧
定義棧的資料結構,請在該型別中實現乙個能夠得到棧的最小元素的min函式。在該棧中,呼叫min push及pop的時間複雜度都是o 1 思路 利用乙個輔助棧來存放最小值 棧 3,4,2,1 輔助棧 3,3,2,1 每入棧一次,就與輔助棧頂比較大小,如果小就入棧,如果大就入棧當前的輔助棧頂 當出棧時,輔...
面試題30 包含min函式的棧
定義棧的資料結構,請在該型別中實現乙個能夠得到棧的最小元素的 min 函式在該棧中,呼叫 min push 及 pop 的時間複雜度都是 o 1 示例 minstack minstack new minstack minstack.push 2 minstack.push 0 minstack.pu...
面試題30 包含min函式的棧
思路 使用輔助棧。棧a實現正常的push,pop,top函式。棧b在每次棧apush的時候判斷,棧頂元素是否 要push進棧a的元素。注意的點 1.if b.empty b.peek x 此處必須要 因為在 情況下,push 0 push 0 pop 棧b就沒有元素了。2.pop 函式中,a.pop...