#leetCode刷题纪实 Day7

https://leetcode-cn.com/problems/implement-stack-using-queues/

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空


注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

小菜鸡的尝试:

这次是一题用队列模拟栈,因为昨天的题目让自己不是一头雾水,做起来还是比较轻松的。

一遍过还是比较快乐的!

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-stack-using-queues
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/xyy999/p/11795220.html
今日推荐