栈————用栈实现队列

 1 class MyQueue {
 2 public:
 3     /** Initialize your data structure here. */
 4     MyQueue() {
 5         
 6     }
 7     stack<int> a;
 8     stack<int> b;
 9     /** Push element x to the back of queue. */
10     void push(int x) {
11         a.push(x);
12     }
13     
14     /** Removes the element from in front of queue and returns that element. */
15     int pop() {
16         int len=a.size();
17         for(int i=0;i<len;i++){
18             b.push(a.top());
19             a.pop();
20         }
21         int tmp=b.top();
22         b.pop();
23         for(int i=0;i<len-1;i++){
24             a.push(b.top());
25             b.pop();
26         }
27         return tmp;
28     }
29     
30     /** Get the front element. */
31     int peek() {
32         int len=a.size();
33         for(int i=0;i<len;i++){
34             b.push(a.top());
35             a.pop();
36         }
37         int tmp=b.top();
38         for(int i=0;i<len;i++){
39             a.push(b.top());
40             b.pop();
41         }
42         return tmp;
43     }
44     
45     /** Returns whether the queue is empty. */
46     bool empty() {
47         return a.empty();
48     }
49 };
50 
51 /**
52  * Your MyQueue object will be instantiated and called as such:
53  * MyQueue* obj = new MyQueue();
54  * obj->push(x);
55  * int param_2 = obj->pop();
56  * int param_3 = obj->peek();
57  * bool param_4 = obj->empty();
58  */

 

posted @ 2019-06-15 19:43  Austin_anheqiao  阅读(123)  评论(0编辑  收藏  举报