Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
-
class MinStack { public: void push(int x) { stack1.push(x); if(stack2.empty()) stack2.push(x); else{ int tmp=stack2.top(); if(x>tmp) stack2.push(tmp); else stack2.push(x); } } void pop() { if((!stack1.empty())&&(!stack2.empty())){ stack1.pop(); stack2.pop(); } else cout<<"EMPTY!"<<endl; } int top() { if(!stack1.empty()) return stack1.top(); } int getMin() { if(!stack2.empty()) return stack2.top(); } private: stack<int> stack1; stack<int> stack2; };
时间: 2024-11-14 08:39:14