File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -359,6 +359,71 @@ class MyStack:
359
359
360
360
Go:
361
361
362
+ ``` go
363
+ type MyStack struct {
364
+ queue []int // 创建一个队列
365
+ }
366
+
367
+
368
+ /* * Initialize your data structure here. */
369
+ func Constructor () MyStack {
370
+ return MyStack{ // 初始化
371
+ queue:make ([]int ,0 ),
372
+ }
373
+ }
374
+
375
+
376
+ /* * Push element x onto stack. */
377
+ func (this *MyStack ) Push (x int ) {
378
+ // 添加元素
379
+ this.queue =append (this.queue ,x)
380
+ }
381
+
382
+
383
+ /* * Removes the element on top of the stack and returns that element. */
384
+ func (this *MyStack ) Pop () int {
385
+ n := len (this.queue )-1 // 判断长度
386
+ for n!=0 { // 除了最后一个,其余的都重新添加到队列里
387
+ val := this.queue [0 ]
388
+ this.queue =this.queue [1 :]
389
+ this.queue =append (this.queue ,val)
390
+ n--
391
+ }
392
+ // 弹出元素
393
+ val := this.queue [0 ]
394
+ this.queue =this.queue [1 :]
395
+ return val
396
+
397
+ }
398
+
399
+
400
+ /* * Get the top element. */
401
+ func (this *MyStack ) Top () int {
402
+ // 利用Pop函数,弹出来的元素重新添加
403
+ val := this.Pop ()
404
+ this.queue =append (this.queue ,val)
405
+ return val
406
+ }
407
+
408
+
409
+ /* * Returns whether the stack is empty. */
410
+ func (this *MyStack ) Empty () bool {
411
+ return len (this.queue )==0
412
+ }
413
+
414
+
415
+ /* *
416
+ * Your MyStack object will be instantiated and called as such:
417
+ * obj := Constructor();
418
+ * obj.Push(x);
419
+ * param_2 := obj.Pop();
420
+ * param_3 := obj.Top();
421
+ * param_4 := obj.Empty();
422
+ */
423
+ ```
424
+
425
+
426
+
362
427
javaScript:
363
428
364
429
使用数组(push, shift)模拟队列
You can’t perform that action at this time.
0 commit comments