1 class MyQueue 2 { 3 private: 4 stack<int> st; 5 public: 6 /** Initialize your data structure here. */ 7 MyQueue() { 8 9 } 10 11 /** Push element x to the back of queue. */ 12 void push(int x) 13 { 14 stack<int> cur; 15 if(!st.empty()) 16 while(!st.empty()) 17 { 18 int i=st.top(); 19 cur.push(i); 20 st.pop(); 21 } 22 cur.push(x); 23 while(!cur.empty()) 24 { 25 int j=cur.top(); 26 st.push(j); 27 cur.pop(); 28 } 29 } 30 31 /** Removes the element from in front of queue and returns that element. */ 32 int pop() 33 { 34 int i=st.top(); 35 st.pop(); 36 return i; 37 } 38 39 /** Get the front element. */ 40 int peek() 41 { 42 return st.top(); 43 } 44 45 /** Returns whether the queue is empty. */ 46 bool empty() 47 { 48 return st.empty(); 49 } 50 }; 51 52 /** 53 * Your MyQueue object will be instantiated and called as such: 54 * MyQueue obj = new MyQueue(); 55 * obj.push(x); 56 * int param_2 = obj.pop(); 57 * int param_3 = obj.peek(); 58 * bool param_4 = obj.empty(); 59 */
用栈模拟队列,俩栈倒过来倒过去的,完事儿