- 题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
- 思路:push的时候塞入stack1。要pop时,此时先进的元素在栈底,当stack2为空时应该先把stack1的元素逐个弹出来同时弹入stack2,此时先入的元素在stack2。若pop时,stack2非空,则先进的元素直接就在stack2栈顶,直接弹出stack2的栈顶元素即可。
code:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
if (stack2.empty())
return NULL;
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};