題目描述
定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。
代碼
class Solution {
public:
void push(int value) {
stack1.push(value);
if(stack2.size()==0||stack2.top()>value)
stack2.push(value);
}
void pop() {
if(stack1.size()>0)
{
if(stack1.top()==stack2.top())
stack2.pop();
stack1.pop();
}
}
int top() {
int ret=0;
if(stack1.size()>0)
{
ret= stack1.top();
}
return ret;
}
int min() {
int ret=0;
if(stack1.size()>0)
{
ret=stack2.top();
}
return ret;
}
private:
stack<int> stack1;
stack<int> stack2;
};