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.
两个栈来实现,其中一个odinarystack进行正常的push,pop,top操作,另一个minstack来存储每次压栈后最小的值
class MinStack {
private:
stack<int> odinarystack;
stack<int> minstack;
public:
void push(int x) {
odinarystack.push(x);
if(minstack.empty() || x <= minstack.top()){
minstack.push(x);
}
}
void pop() {
if(!odinarystack.empty()){
if(odinarystack.top() == minstack.top())
minstack.pop();
odinarystack.pop();
}
}
int top() {
if(!odinarystack.empty())
return odinarystack.top();
else
return NULL;
}
int getMin() {
if(!minstack.empty())
return minstack.top();
else
return NULL;
}
};