其他分享
首页 > 其他分享> > 232. 用栈实现队列(栈)

232. 用栈实现队列(栈)

作者:互联网

232. 用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

说明:

 

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
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

 

提示:

 1 class MyQueue {
 2 public:
 3     stack<int> s1; // 栈顶存放队尾,栈底存放队首,当s2为空时,s1栈顶就是队尾
 4     stack<int> s2; // 辅助栈,当s1为空时,s2的栈顶就是队首
 5     MyQueue() {
 6 
 7     }
 8     
 9     void push(int x) {
10         // 当s2为空时,s1栈顶就是队尾
11         if (s2.empty()) {
12             s1.push(x);
13             return;
14         }
15         // 如果辅助栈非空,需要将辅助栈的元素都追加到s1后,再在s1的栈顶添加新元素
16         while(!s2.empty()) {
17             int top = s2.top();
18             s2.pop();
19             s1.push(top);
20         }
21         s1.push(x);
22         return;
23     }
24     
25     int pop() {
26         // 当s1为空时,s2的栈顶就是队首
27         if (s1.empty()) {
28             int top = s2.top();
29             s2.pop();
30             return top;
31         }
32         while (!s1.empty()) {
33             int top = s1.top();
34             s1.pop();
35             s2.push(top);
36         }
37         int top = s2.top();
38         s2.pop();
39         return top;
40     }
41     
42     int peek() {
43         // 当s1为空时,s2的栈顶就是队首
44         if (s1.empty()) {
45             return s2.top();
46         }
47         while (!s1.empty()) {
48             int top = s1.top();
49             s1.pop();
50             s2.push(top);
51         }
52         return s2.top();
53     }
54     
55     bool empty() {
56         return s1.empty() && s2.empty();
57     }
58 };
59 
60 /**
61  * Your MyQueue object will be instantiated and called as such:
62  * MyQueue* obj = new MyQueue();
63  * obj->push(x);
64  * int param_2 = obj->pop();
65  * int param_3 = obj->peek();
66  * bool param_4 = obj->empty();
67  */

 

标签:队列,s2,top,pop,用栈,empty,push,s1,232
来源: https://www.cnblogs.com/MGFangel/p/16220240.html