题解
模拟题。
比较清晰的做法:
stack1用于Push
stack2用于Pop
如果stack2为空 则stack1的元素都要压入stack2
这样不会出现问题
因为如果stack2不为空,则弹出的元素一定是满足队列的特点的,但stack2不为空时不能再往stack2中压入元素。
例如:
push(1) push(2) push(3) pop() push(4)
stack1: 3,2,1
pop时,需要输出1,将stack1的元素压入stack2变成1,2,3
再压入4时不能压入stack2, 否则变成了4,2,3无论如何都不能下一次弹出2
代码:
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 ans = stack2.top();
stack2.pop();
return ans;
}
private:
stack<int> stack1;
stack<int> stack2;
};