LeetCode 232 Implement Queue using Stacks 两个栈实现队列

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

 

posted on 2018-03-09 16:24  lina2014  阅读(126)  评论(0编辑  收藏  举报

导航