232. Implement Queue using Stacks

问题:

设计数据结构,使用stack实现queue。

实现以下功能:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.
Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
 

Constraints:

1 <= x <= 9
At most 100 calls will be made to push, pop, peek, and empty.
All the calls to pop and peek are valid.

  

解法:双栈->实现队列

参考labuladong解析

 

 

 

重点在:

查队列头peek 和 出队pop

实现方法:

  • 若s2中元素,那么优先出队
  • 若s2中元素,那么s1.pop排空->s2.push

 

代码参考:

 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         s1.push(x);
11     }
12     
13     /** Removes the element from in front of queue and returns that element. */
14     int pop() {
15         int res = peek();
16         s2.pop();
17         return res;
18     }
19     
20     /** Get the front element. */
21     int peek() {
22         if (s2.empty()) {
23             while(!s1.empty()) {
24                 s2.push(s1.top());
25                 s1.pop();
26             }
27         }
28         return s2.top();
29     }
30     
31     /** Returns whether the queue is empty. */
32     bool empty() {
33         return s2.empty() && s1.empty();
34     }
35 private:
36     stack<int> s1, s2;
37 };
38 
39 /**
40  * Your MyQueue object will be instantiated and called as such:
41  * MyQueue* obj = new MyQueue();
42  * obj->push(x);
43  * int param_2 = obj->pop();
44  * int param_3 = obj->peek();
45  * bool param_4 = obj->empty();
46  */

 

posted @ 2021-04-18 14:39  habibah_chang  阅读(36)  评论(0编辑  收藏  举报