题目:
解答:
第一个栈保存正常push,另一个保存逆序栈,也就是队列顺序。第二个优先于第一个栈。
1 class MyQueue { 2 public: 3 stack<int> que; 4 stack<int> temp; 5 /** Initialize your data structure here. */ 6 MyQueue() 7 { 8 } 9 10 /** Push element x to the back of queue. */ 11 void push(int x) 12 { 13 que.push(x); 14 } 15 16 /** Removes the element from in front of queue and returns that element. */ 17 int pop() 18 { 19 if(!temp.empty()) 20 { 21 int value = temp.top(); 22 temp.pop(); 23 return value; 24 } 25 else 26 { 27 while(!que.empty()) 28 { 29 temp.push(que.top()); 30 que.pop(); 31 } 32 int value = temp.top(); 33 temp.pop(); 34 return value; 35 } 36 } 37 38 /** Get the front element. */ 39 int peek() 40 { 41 if(!temp.empty()) 42 { 43 return temp.top(); 44 } 45 else 46 { 47 while(!que.empty()) 48 { 49 temp.push(que.top()); 50 que.pop(); 51 } 52 return temp.top(); 53 } 54 } 55 56 /** Returns whether the queue is empty. */ 57 bool empty() 58 { 59 return que.empty() && temp.empty(); 60 } 61 }; 62 63 /** 64 * Your MyQueue object will be instantiated and called as such: 65 * MyQueue* obj = new MyQueue(); 66 * obj->push(x); 67 * int param_2 = obj->pop(); 68 * int param_3 = obj->peek(); 69 * bool param_4 = obj->empty(); 70 */
原文:https://www.cnblogs.com/ocpc/p/12861091.html