@@ -64,6 +64,17 @@ myStack.empty(); // 返回 False
64
64
65
65
<!-- 这里可写通用的实现逻辑 -->
66
66
67
+ ** 方法一:两个队列**
68
+
69
+ 我们使用两个队列 $q_1$ 和 $q_2$,其中 $q_1$ 用于存储栈中的元素,而 $q_2$ 用于辅助实现栈的操作。
70
+
71
+ - ` push ` 操作:将元素压入 $q_2$,然后将 $q_1$ 中的元素依次弹出并压入 $q_2$,最后交换 $q_1$ 和 $q_2$ 的引用。时间复杂度 $O(n)$。
72
+ - ` pop ` 操作:直接弹出 $q_1$ 的队首元素。时间复杂度 $O(1)$。
73
+ - ` top ` 操作:直接返回 $q_1$ 的队首元素。时间复杂度 $O(1)$。
74
+ - ` empty ` 操作:判断 $q_1$ 是否为空。时间复杂度 $O(1)$。
75
+
76
+ 空间复杂度 $O(n)$,其中 $n$ 是栈中元素的个数。
77
+
67
78
<!-- tabs:start -->
68
79
69
80
### ** Python3**
@@ -72,38 +83,25 @@ myStack.empty(); // 返回 False
72
83
73
84
``` python
74
85
class MyStack :
86
+
75
87
def __init__ (self ):
76
- """
77
- Initialize your data structure here.
78
- """
79
- self .q = []
88
+ self .q1 = deque()
89
+ self .q2 = deque()
80
90
81
91
def push (self , x : int ) -> None :
82
- """
83
- Push element x onto stack.
84
- """
85
- self .q.append(x)
86
- n = len (self .q)
87
- for i in range (1 , n):
88
- self .q.append(self .q.pop(0 ))
92
+ self .q2.append(x)
93
+ while self .q1:
94
+ self .q2.append(self .q1.popleft())
95
+ self .q1, self .q2 = self .q2, self .q1
89
96
90
97
def pop (self ) -> int :
91
- """
92
- Removes the element on top of the stack and returns that element.
93
- """
94
- return self .q.pop(0 )
98
+ return self .q1.popleft()
95
99
96
100
def top (self ) -> int :
97
- """
98
- Get the top element.
99
- """
100
- return self .q[0 ]
101
+ return self .q1[0 ]
101
102
102
103
def empty (self ) -> bool :
103
- """
104
- Returns whether the stack is empty.
105
- """
106
- return len (self .q) == 0
104
+ return len (self .q1) == 0
107
105
108
106
109
107
# Your MyStack object will be instantiated and called as such:
@@ -119,37 +117,36 @@ class MyStack:
119
117
<!-- 这里可写当前语言的特殊实现逻辑 -->
120
118
121
119
``` java
122
- class MyStack {
120
+ import java.util.Deque ;
123
121
124
- private Deque<Integer > q;
122
+ class MyStack {
123
+ private Deque<Integer > q1 = new ArrayDeque<> ();
124
+ private Deque<Integer > q2 = new ArrayDeque<> ();
125
125
126
- /* * Initialize your data structure here. */
127
126
public MyStack () {
128
- q = new ArrayDeque<> ();
127
+
129
128
}
130
129
131
- /* * Push element x onto stack. */
132
130
public void push (int x ) {
133
- q. offerLast(x);
134
- int n = q. size();
135
- while (n-- > 1 ) {
136
- q. offerLast(q. pollFirst());
131
+ q2. offer(x);
132
+ while (! q1. isEmpty()) {
133
+ q2. offer(q1. poll());
137
134
}
135
+ Deque<Integer > q = q1;
136
+ q1 = q2;
137
+ q2 = q;
138
138
}
139
139
140
- /* * Removes the element on top of the stack and returns that element. */
141
140
public int pop () {
142
- return q . pollFirst ();
141
+ return q1 . poll ();
143
142
}
144
143
145
- /* * Get the top element. */
146
144
public int top () {
147
- return q . peekFirst ();
145
+ return q1 . peek ();
148
146
}
149
147
150
- /* * Returns whether the stack is empty. */
151
148
public boolean empty () {
152
- return q . isEmpty();
149
+ return q1 . isEmpty();
153
150
}
154
151
}
155
152
@@ -163,6 +160,138 @@ class MyStack {
163
160
*/
164
161
```
165
162
163
+ ### ** C++**
164
+
165
+ ``` cpp
166
+ class MyStack {
167
+ public:
168
+ MyStack() {
169
+
170
+ }
171
+
172
+ void push (int x) {
173
+ q2.push(x);
174
+ while (!q1.empty()) {
175
+ q2.push(q1.front());
176
+ q1.pop();
177
+ }
178
+ swap(q1, q2);
179
+ }
180
+
181
+ int pop() {
182
+ int x = q1.front();
183
+ q1.pop();
184
+ return x;
185
+ }
186
+
187
+ int top() {
188
+ return q1.front();
189
+ }
190
+
191
+ bool empty() {
192
+ return q1.empty();
193
+ }
194
+
195
+ private:
196
+ queue<int > q1;
197
+ queue<int > q2;
198
+ };
199
+
200
+ /**
201
+ * Your MyStack object will be instantiated and called as such:
202
+ * MyStack* obj = new MyStack();
203
+ * obj->push(x);
204
+ * int param_2 = obj->pop();
205
+ * int param_3 = obj->top();
206
+ * bool param_4 = obj->empty();
207
+ * /
208
+ ```
209
+
210
+ ### **Go**
211
+
212
+ ```go
213
+ type MyStack struct {
214
+ q1 []int
215
+ q2 []int
216
+ }
217
+
218
+ func Constructor() MyStack {
219
+ return MyStack{}
220
+ }
221
+
222
+ func (this *MyStack) Push(x int) {
223
+ this.q2 = append(this.q2, x)
224
+ for len(this.q1) > 0 {
225
+ this.q2 = append(this.q2, this.q1[0])
226
+ this.q1 = this.q1[1:]
227
+ }
228
+ this.q1, this.q2 = this.q2, this.q1
229
+ }
230
+
231
+ func (this *MyStack) Pop() int {
232
+ x := this.q1[0]
233
+ this.q1 = this.q1[1:]
234
+ return x
235
+ }
236
+
237
+ func (this *MyStack) Top() int {
238
+ return this.q1[0]
239
+ }
240
+
241
+ func (this *MyStack) Empty() bool {
242
+ return len(this.q1) == 0
243
+ }
244
+
245
+ /**
246
+ * Your MyStack object will be instantiated and called as such:
247
+ * obj := Constructor();
248
+ * obj.Push(x);
249
+ * param_2 := obj.Pop();
250
+ * param_3 := obj.Top();
251
+ * param_4 := obj.Empty();
252
+ */
253
+ ```
254
+
255
+ ### ** TypeScript**
256
+
257
+ ``` ts
258
+ class MyStack {
259
+ q1: number [] = [];
260
+ q2: number [] = [];
261
+
262
+ constructor () {}
263
+
264
+ push(x : number ): void {
265
+ this .q2 .push (x );
266
+ while (this .q1 .length ) {
267
+ this .q2 .push (this .q1 .shift ()! );
268
+ }
269
+ [this .q1 , this .q2 ] = [this .q2 , this .q1 ];
270
+ }
271
+
272
+ pop(): number {
273
+ return this .q1 .shift ()! ;
274
+ }
275
+
276
+ top(): number {
277
+ return this .q1 [0 ];
278
+ }
279
+
280
+ empty(): boolean {
281
+ return this .q1 .length === 0 ;
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Your MyStack object will be instantiated and called as such:
287
+ * var obj = new MyStack()
288
+ * obj.push(x)
289
+ * var param_2 = obj.pop()
290
+ * var param_3 = obj.top()
291
+ * var param_4 = obj.empty()
292
+ */
293
+ ```
294
+
166
295
### ** ...**
167
296
168
297
```
0 commit comments