标签:c++ leetcode data structure
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
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;
};标签:c++ leetcode data structure
原文地址:http://blog.csdn.net/eliza1130/article/details/44752701