232. 用栈实现队列

两个栈,一个用来接收,一个用来弹出

 1 class MyQueue {
 2 public:
 3     stack<int> in;
 4     stack<int> out;
 5     MyQueue() {
 6 
 7     }
 8     
 9     void push(int x) {
10         in.push(x);
11     }
12     
13     int pop() {
14         if(out.empty()){
15             while(!in.empty()){
16                 out.push(in.top());
17                 in.pop();
18             }
19         }
20         int tmp = out.top();
21         out.pop();
22         return tmp;
23     }
24     
25     int peek() {
26         if(out.empty()){
27             while(!in.empty()){
28                 out.push(in.top());
29                 in.pop();
30             }
31         }
32         return out.top();
33     }
34     
35     bool empty() {
36         return in.empty() && out.empty();
37     }
38 };
39 
40 /**
41  * Your MyQueue object will be instantiated and called as such:
42  * MyQueue* obj = new MyQueue();
43  * obj->push(x);
44  * int param_2 = obj->pop();
45  * int param_3 = obj->peek();
46  * bool param_4 = obj->empty();
47  */

225. 用队列实现栈

 1 class MyStack {
 2 public:
 3     queue<int> queue;
 4     MyStack() {
 5 
 6     }
 7     
 8     void push(int x) {
 9         queue.push(x);
10     }
11     
12     int pop() {
13         int size = queue.size();
14         while(--size){
15             push(queue.front());
16             queue.pop();
17         }
18         int tmp = queue.front();
19         queue.pop();
20         return tmp;
21     }
22     
23     int top() {
24         return queue.back();
25     }
26     
27     bool empty() {
28         return queue.empty();
29     }
30 };
31 
32 /**
33  * Your MyStack object will be instantiated and called as such:
34  * MyStack* obj = new MyStack();
35  * obj->push(x);
36  * int param_2 = obj->pop();
37  * int param_3 = obj->top();
38  * bool param_4 = obj->empty();
39  */