题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:用栈1负责入队(当然,如果你想栈2负责入队也是可以的),栈2负责出队操作,入队操作无需考虑栈里是否为空(这里不考虑上溢情况),而出队操作必须考虑栈是否为空,因为栈为空,就必须从栈1获取元素,付给栈2,然后栈2才能执行出队操作。
class Solution
{
public:
void push(int node)
{
stack1.push(node); //栈1负责入队工作
}
int pop()
{
if (stack2.empty())
{
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
int result = stack2.top();
stack2.pop();
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};