刷题笔记(四)——利用栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:一个栈stack1作为push,将入队的元素push到该栈中;另一个栈stack2作为pop,出队时,若该栈不为空,则直接pop该栈中的元素,若为空时,需先将stack1中的元素逐个pop,再push到stack2中。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int a;
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
a=stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};