题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack2.empty()){ while(stack1.empty() == false){ int top_val = stack1.top(); stack2.push(top_val); stack1.pop(); } } int top_val = stack2.top(); stack2.pop(); return top_val; } private: stack<int> stack1; stack<int> stack2; };
stack1作为数据栈,将数据push进该栈中。
stack2作为辅助栈,负责pop(). 如果辅助栈为空,则将数据栈中元素全部转移到辅助栈中,然后返回栈顶元素。