Skip to content

Commit 40b3dfd

Browse files
committed
Update 0225. 用队列实现栈.md
1 parent 748f892 commit 40b3dfd

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

Solutions/0225. 用队列实现栈.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,50 @@
55

66
## 题目大意
77

8-
要求:仅使用两个队列实现一个后入先出(LIFO)的栈。
8+
**要求**:仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的四种操作:`push``top``pop``empty`
9+
10+
要求实现 `MyStack` 类:
11+
12+
- `void push(int x)` 将元素 `x` 压入栈顶。
13+
- `int pop()` 移除并返回栈顶元素。
14+
- `int top()` 返回栈顶元素。
15+
- `boolean empty()` 如果栈是空的,返回 `True`;否则,返回 `False`
16+
17+
**说明**
18+
19+
- 只能使用队列的基本操作 —— 也就是 `push to back``peek/pop from front``size``is empty` 这些操作。
20+
- 所使用的语言也许不支持队列。 你可以使用 `list` (列表)或者 `deque`(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
21+
22+
**示例**
23+
24+
```Python
25+
输入:
26+
["MyStack", "push", "push", "top", "pop", "empty"]
27+
[[], [1], [2], [], [], []]
28+
输出:
29+
[null, null, null, 2, 2, false]
30+
31+
解释:
32+
MyStack myStack = new MyStack();
33+
myStack.push(1);
34+
myStack.push(2);
35+
myStack.top(); // 返回 2
36+
myStack.pop(); // 返回 2
37+
myStack.empty(); // 返回 False
38+
```
939

1040
## 解题思路
1141

42+
### 思路 1:双队列
43+
1244
使用两个队列。`pushQueue` 用作入栈,`popQueue` 用作出栈。
1345

1446
- `push` 操作:将新加入的元素压入 `pushQueue` 队列中,并且将之前保存在 `popQueue` 队列中的元素从队头开始依次压入 `pushQueue` 中,此时 `pushQueue` 队列中头节点存放的是新加入的元素,尾部存放的是之前的元素。 而 `popQueue` 则为空。再将 `pushQueue``popQueue` 相互交换,保持 `pushQueue` 为空,`popQueue` 则用于 `pop``top` 等操作。
1547
- `pop` 操作:直接将 `popQueue` 队头元素取出。
1648
- `top` 操作:返回 `popQueue` 队头元素。
1749
- `empty`:判断 `popQueue` 是否为空。
1850

19-
## 代码
51+
### 思路 1:代码
2052

2153
```Python
2254
class MyStack:
@@ -59,3 +91,7 @@ class MyStack:
5991
return not self.popQueue
6092
```
6193

94+
### 思路 1:复杂度分析
95+
96+
- **时间复杂度**:入栈操作的时间复杂度为 $O(n)$。出栈、取栈顶元素、判断栈是否为空的时间复杂度为 $O(1)$。
97+
- **空间复杂度**:$O(n)$。

0 commit comments

Comments
 (0)