class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int res;
if(stack2.size()>0)//栈2中有元素,则先弹出来
{
res=stack2.top();
stack2.pop();
}
else if(stack1.size()>0)//栈2中没有元素,且栈1中有元素,将栈1中的元素弹出后再压入栈2,弹出栈2的顶部元素即为出队
{
while(stack1.size()>0)
{
int data=stack1.top();
stack1.pop();
stack2.push(data);
}
res=stack2.top();
stack2.pop();
}
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
用两个栈来实现一个队列,完成队列的Push和Pop操作( 队列中的元素为int类型)
最新推荐文章于 2022-07-20 17:11:56 发布