思路:利用两个栈,stack1push后,当pop时,放入stack2push后,返回Stack2的top()。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
int tmp = stack2.top();
stack2.pop();
return tmp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
利用vector实现。
class TwoStack{
public:
stack<int> stack_push,stack_pop;
vector twoStack(vector<int> ope,int n)
{
vector<int> res;
int i;
for(i=0;i<n;i++)
{
if(ope[i]>0)
push(ope[i]);
if(ope[i]==0)
res.push_back(pop());
if(ope[i]<0)
exit(-1);
}
return res;
}
void push(int value)
{
stack_push.push(value);
}
int pop()
{
if(stack_pop.empty())
while(!stack_push.empty())
{
stack_pop.push(stack_push.top());
stack_push.pop();
}
int res=stack_pop.top();
stack_pop.pop();
return res;
}
};