You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: en/1-1000/225-implement-stack-using-queues.md
+36-3Lines changed: 36 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -53,13 +53,18 @@ Can you implement the stack using only one queue?
53
53
1. Option 1: Simplify the `push(x)` operation and complicate the `pop()` and `top()` operations. When `pop()` or `top()`, you need to find the last data with effort.
54
54
2. Option 2: Simplify the `pop()` and `top()` operations and complicate the `push(x)` operation. When `push(x)`, you need to insert `x` into the front of the queue with effort.
55
55
3. Advantages of Option 2: Less code; easier to understand logically because it sorts the data in the queue according to the `last in, first out` rule.
56
-
4. This article mainly introduces `Option 2`, and the code of `Option 1` is attached in `Python` to facilitate readers to compare the two solutions.
56
+
4. This article mainly introduces `Option 2`, and the code of `Option 1` is attached in `Python`section to facilitate readers to compare the two solutions.
- You can use only one queue to make it. The only change is in the `push` method. Just find a way to insert `x` to the front of the queue without using another `queue_temp`.
64
+
- When implementing the `push` method, first `queue.push(x)`, then execute `queue.length - 1` times `queue.push(queue.pop())`. The complete code is attached in `JavaScript` section.
65
+
62
66
## JavaScript
67
+
### Solution for option 2
63
68
```javascript
64
69
varMyStack=function () {
65
70
this.queue= []
@@ -95,8 +100,36 @@ MyStack.prototype.empty = function () {
95
100
};
96
101
```
97
102
103
+
### Follow-up solution: use only one queue
104
+
```javascript
105
+
varMyStack=function () {
106
+
this.queue= []
107
+
};
108
+
109
+
MyStack.prototype.push=function (x) {
110
+
this.queue.push(x)
111
+
112
+
_.times(
113
+
this.queue.length-1,
114
+
() =>this.queue.push(this.queue.shift())
115
+
)
116
+
};
117
+
118
+
MyStack.prototype.pop=function () {
119
+
returnthis.queue.shift()
120
+
};
121
+
122
+
MyStack.prototype.top=function () {
123
+
returnthis.queue[0]
124
+
};
125
+
126
+
MyStack.prototype.empty=function () {
127
+
returnthis.queue.length===0
128
+
};
129
+
```
130
+
98
131
## Python
99
-
### Solution 1: Not recommended, for comparison only.
132
+
### Solution for option 1: Not recommended, for comparison only.
100
133
```python
101
134
classMyStack:
102
135
def__init__(self):
@@ -139,7 +172,7 @@ class MyStack:
139
172
returnlen(self.queue) ==0
140
173
```
141
174
142
-
### Solution 2: The recommended solution. It is short and easy to understand.
175
+
### Solution for option 2: It is short and easy to understand (recommended).
0 commit comments