Skip to content

Commit 6609258

Browse files
Merge pull request youngyangyang04#697 from baici1/master
添加225. 用队列实现栈 go版本
2 parents d6b72d1 + 71a24c5 commit 6609258

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,71 @@ class MyStack:
359359

360360
Go:
361361

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+
362427
javaScript:
363428

364429
使用数组(push, shift)模拟队列

0 commit comments

Comments
 (0)