设计一个具有min函数的stack
此题目来自于Crack the Coding Interview 3-2
3 2 How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and in should all operate in O(1) time.
思路是弄2个stack,一个realStack,存放真正的数据;另外一个是minStack,对于minStack元素中的每一个元素的意义是:push到该位置的时候,当前最小元素的值。每次push进新元素的时候,更新minStack的值;每次pop的时候,由于minStack的定义,所以只需把minStack和realStack一起进行一次pop操作就好了。
#include <iostream> #include <stack> using namespace std; class StackWithMin{ public: void push(int value); void pop(); int min(); int top(); private: stack<int> realStack; stack<int> minStack; }; void StackWithMin::push(int value) { int currMin = 0; if (!minStack.empty()) currMin = minStack.top(); else currMin = INT_MAX; if (value < currMin) minStack.push(value); else minStack.push(minStack.top()); realStack.push(value); } void StackWithMin::pop() { if (realStack.empty() || minStack.empty()) { cout<<"stack empty!"<<endl; return; } realStack.pop(); minStack.pop(); } int StackWithMin::min() { if (realStack.empty() || minStack.empty()) { cout<<"stack empty!"<<endl; return INT_MAX; } return minStack.top(); } int StackWithMin::top() { if (realStack.empty() || minStack.empty()) { cout<<"stack empty!"<<endl; return -1; } return realStack.top(); } int main() { StackWithMin stk; for (int i = 0; i < 10; i++) { int value = rand()%150; cout<<"Pushing : "<<value<<endl; stk.push(value); } cout<<"Push 10 Elements and current min is : "<<stk.min()<<endl<<endl; for (int i = 0; i < 5; i++) { int value = stk.top(); cout<<"Poping : "<<value<<endl; stk.pop(); } cout<<"After pop 5 Elements, current min is : "<<stk.min()<<endl; return 0; }
EOF