题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型
解题思路:
stack1用来做入队列,stack2用来做出队列。当stack2为空时,将stack1中的所有元素压入stack2中,同时将stack1中的元素出栈。当stack2不为空时,直接将栈顶元素出队。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while(stack2.empty())
{
while(! stack1.empty())
{
int tmp = stack1.top();
stack2.push(tmp);
stack1.pop();
}
}
int tmp = stack2.top();
stack2.pop();
return tmp;
}
private:
stack<int> stack1;
stack<int> stack2;
};