Skip to content

Commit 81502c8

Browse files
Create 225. 用队列实现栈.md
1 parent 65e42b7 commit 81502c8

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

Queue/225. 用队列实现栈.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#### 225. 用队列实现栈
2+
3+
难度:简单
4+
5+
---
6+
7+
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(`push``top``pop``empty`)。
8+
9+
实现 `MyStack` 类:
10+
11+
* `void push(int x)` 将元素 x 压入栈顶。
12+
* `int pop()` 移除并返回栈顶元素。
13+
* `int top()` 返回栈顶元素。
14+
* `boolean empty()` 如果栈是空的,返回 `true` ;否则,返回 `false`
15+
16+
**注意:**
17+
18+
* 你只能使用队列的基本操作 —— 也就是 `push to back``peek/pop from front``size` 和 `is empty` 这些操作。
19+
* 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
20+
21+
**示例:**
22+
23+
```
24+
输入:
25+
["MyStack", "push", "push", "top", "pop", "empty"]
26+
[[], [1], [2], [], [], []]
27+
输出:
28+
[null, null, null, 2, 2, false]
29+
30+
解释:
31+
MyStack myStack = new MyStack();
32+
myStack.push(1);
33+
myStack.push(2);
34+
myStack.top(); // 返回 2
35+
myStack.pop(); // 返回 2
36+
myStack.empty(); // 返回 False
37+
```
38+
39+
**提示:**
40+
41+
* `1 <= x <= 9`
42+
* 最多调用`100``push``pop``top``empty`
43+
* 每次调用 `pop``top` 都保证栈不为空
44+
45+
**进阶:** 你能否仅用一个队列来实现栈。
46+
47+
---
48+
49+
队列:
50+
51+
固定第一个队列为主队列,第二个队列为辅助队列;
52+
53+
- 调用 `push()` 时,每次都向主队列插入数据;
54+
- 调用 `pop()` 时,将主队列里的前 `size() - 1` 个数按队列弹出的顺序插入到辅助队列中,清空主队列后再交换主队列和辅助队列;
55+
- 调用 `top()` 时,先调用 `pop()` 方法保存变量,再插入到主队列中,最后返回该变量;
56+
- 调用 `isEmpty()` 时,直接调用主函数的 `isEmpty()` 方法即可。
57+
58+
```Java
59+
class MyStack {
60+
ArrayDeque<Integer> q1, q2;
61+
62+
public MyStack() {
63+
q1 = new ArrayDeque<Integer>();
64+
q2 = new ArrayDeque<Integer>();
65+
}
66+
67+
public void push(int x) {
68+
q1.offer(x);
69+
}
70+
71+
public int pop() {
72+
int sz = q1.size();
73+
while(--sz >= 1){
74+
q2.offer(q1.poll());
75+
}
76+
ArrayDeque<Integer> temp = q1;
77+
q1 = q2;
78+
q2 = temp;
79+
return q2.poll();
80+
}
81+
82+
public int top() {
83+
int temp = pop();
84+
q1.offer(temp);
85+
return temp;
86+
}
87+
88+
public boolean empty() {
89+
return q1.isEmpty();
90+
}
91+
}
92+
93+
/**
94+
* Your MyStack object will be instantiated and called as such:
95+
* MyStack obj = new MyStack();
96+
* obj.push(x);
97+
* int param_2 = obj.pop();
98+
* int param_3 = obj.top();
99+
* boolean param_4 = obj.empty();
100+
*/
101+
```

0 commit comments

Comments
 (0)