题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
1当队列进行push入队列操作时,就将元素放入stack1
2当队列进行pop出队列操作时,先查看stack2是否为空,若不为空,则从stack2删除一个元素;若为空,就将此时stack1中的所有元素依次放入stack2中,最后再对stack2进行出栈操作
代码:
class Solution { public: void push(int node) { stack1.push(node); } int pop() { int temp1; if(!stack2.empty()) { temp1 = stack2.top(); stack2.pop(); } else { while(!stack1.empty()) { int temp = stack1.top(); stack1.pop(); stack2.push(temp); } temp1 = stack2.top(); stack2.pop(); } return temp1; } private: stack<int> stack1; stack<int> stack2; };