题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
stack1用于出栈
stack2用于入栈
stack1出栈之前,stack2要全部挪入stack1
stack2入栈之前,stack1要全部挪入stack2
class Solution { public: //sour-->des void move(stack<int>& sour, stack<int>& des){ while(!sour.empty()){ int cur = sour.top(); sour.pop(); des.push(cur); } } void push(int node) { move(stack1, stack2); stack2.push(node); } int pop() { move(stack2, stack1); if(stack1.empty()) return -1; int res = stack1.top(); stack1.pop(); return res; } private: stack<int> stack1; //pop栈 stack<int> stack2; //push栈 };