LeetCode OJ:Implement Stack using Queues(队列实现栈)

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack)

类似上一题的两个栈实现队列,但是有点不同,具体的见下面的注释:

 1 class Stack {
 2 public:
 3     // Push element x onto stack.
 4     void push(int x) {
 5         q1.push(x);
 6     }
 7 
 8     // Removes the element on top of the stack.
 9     void pop() {
10         int tmp = q1.front();//注意这里的实现和双栈实现队列的方式是不相同的
11         q1.pop();
12         while(!q1.empty()){
13             q2.push(tmp);
14             tmp = q1.front();
15             q1.pop();
16         }
17         swap(q1,q2);
18     }
19 
20     // Get the top element.
21     int top() {
22         int tmp = q1.front();
23         q1.pop();
24         while(!q1.empty()){
25             q2.push(tmp);
26             tmp = q1.front();
27             q1.pop();
28         }
29         q2.push(tmp);
30         swap(q1, q2);//用swap即可,无须再向上次那样再倒回去
31         return tmp;
32     }
33 
34     // Return whether the stack is empty.
35     bool empty() {
36         return q1.empty();            
37     }
38 private:
39     queue<int> q1;
40     queue<int> q2;
41 };

 

posted @ 2016-01-06 22:25  eversliver  阅读(242)  评论(0编辑  收藏  举报