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
- At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
45
45
- All the calls to `pop` and `top` are valid.
46
46
47
-
### [Follow-up]
48
-
Can you implement the stack using only one queue?
49
-
50
47
## Intuition
51
48
1. Two queues are used, one for input and output, and the other for temporary storage.
52
49
2. There are two options for using queues to simulate the functions of a stack:
@@ -60,11 +57,15 @@ Can you implement the stack using only one queue?
60
57
* Space: `O(n)`.
61
58
62
59
## Follow-up
60
+
Can you implement the stack using only one queue?
61
+
62
+
### Follow-up Intuition
63
63
- 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.
64
+
- When implementing the `push` method, first `queue.push(x)`, so that `x` is inserted at the tail (back) of the queue, but we need to put `x` at the head (front) of the queue.
65
+
- Execute `queue.length - 1` times `queue.push(queue.pop())` to move all the data before `x` to the back of `x`. The complete code is attached in the `JavaScript` section.
65
66
66
67
## JavaScript
67
-
### Solution for option 2
68
+
### "Option 2" solution
68
69
```javascript
69
70
varMyStack=function () {
70
71
this.queue= []
@@ -100,7 +101,7 @@ MyStack.prototype.empty = function () {
100
101
};
101
102
```
102
103
103
-
### Follow-up solution: use only one queue
104
+
### "Follow-up" solution: use only one queue
104
105
```javascript
105
106
varMyStack=function () {
106
107
this.queue= []
@@ -129,7 +130,7 @@ MyStack.prototype.empty = function () {
129
130
```
130
131
131
132
## Python
132
-
### Solution for option 1: Not recommended, for comparison only.
133
+
### "Option 1" solution: Not recommended, for comparison only.
133
134
```python
134
135
classMyStack:
135
136
def__init__(self):
@@ -172,7 +173,7 @@ class MyStack:
172
173
returnnotself.queue
173
174
```
174
175
175
-
### Solution for option 2: It is short and easy to understand (recommended).
176
+
### "Option 2" solution: It is short and easy to understand (recommended).
0 commit comments