用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
思路:push的时候统一push到stack1中;pop的时候先判断stack2是否为空,如果为空,将stack1元素全部出栈,push到stack2中,再从stack2中pop
class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack2.size()==0) { while(stack1.size()) { int tmp=stack1.top(); stack1.pop(); stack2.push(tmp); } } int tmp=stack2.top(); stack2.pop(); return tmp; } private: stack<int> stack1; stack<int> stack2; };