232. Implement Queue using Stacks
仅供自己学习
思路:
这里只用两个栈来模拟队列,因为栈是先进后出,队列是先进先出,所以一个栈instack用来存进来的元素,另一个栈outstack存instack弹出的元素,且若instack要将元素加入进outstack中,只有当outstack空了才能重新加入新进instack得元素,否则顺序将错误。这样队列就能模拟成功
对于每一种功能:
push,只需要将新元素加入instack中即可,暂不需要加入outstack,我们会在pop中加入
pop,首先判断 outstack有没有空,如果有就把instack的元素加入进outstack然后再获取outstack的第一个元素,再pop出来,否则直接top,pop即可
peek,依然是判断outstack有没有空,如果空了就从instack将元素加入,然后return top即可 不用pop
empty,直接判断两个栈有没有空,没有就false,有就true
代码:
1 class MyQueue { 2 private: 3 stack<int> inst,outst; 4 void intoout(){ 5 while(!inst.empty()){ 6 outst.push(inst.top()); 7 inst.pop(); 8 } 9 } 10 public: 11 /** Initialize your data structure here. */ 12 MyQueue() { 13 14 } 15 16 /** Push element x to the back of queue. */ 17 void push(int x) { 18 inst.push(x); 19 } 20 21 /** Removes the element from in front of queue and returns that element. */ 22 int pop() { 23 if(outst.empty()){ 24 intoout(); 25 } 26 auto temp=outst.top(); 27 outst.pop(); 28 return temp; 29 } 30 31 /** Get the front element. */ 32 int peek() { 33 if(outst.empty()) 34 intoout(); 35 return outst.top(); 36 } 37 38 /** Returns whether the queue is empty. */ 39 bool empty() { 40 if(inst.empty()&&outst.empty()) 41 return true; 42 return false; 43 } 44 }; 45 46 /** 47 * Your MyQueue object will be instantiated and called as such: 48 * MyQueue* obj = new MyQueue(); 49 * obj->push(x); 50 * int param_2 = obj->pop(); 51 * int param_3 = obj->peek(); 52 * bool param_4 = obj->empty(); 53 */