Skip to content

Commit

Permalink
Merge pull request youngyangyang04#884 from CJ-cooper6/master
Browse files Browse the repository at this point in the history
添加225. 用队列实现栈 Go 两个队列实现版本
  • Loading branch information
youngyangyang04 committed Nov 7, 2021
2 parents 7351b29 + 5397b5e commit 5561706
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions problems/0225.用队列实现栈.md
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,72 @@ class MyStack:

Go:

使用两个队列实现
```go
type MyStack struct {
//创建两个队列
queue1 []int
queue2 []int
}


func Constructor() MyStack {
return MyStack{ //初始化
queue1:make([]int,0),
queue2:make([]int,0),
}
}


func (this *MyStack) Push(x int) {
//先将数据存在queue2中
this.queue2 = append(this.queue2,x)
//将queue1中所有元素移到queue2中,再将两个队列进行交换
this.Move()
}


func (this *MyStack) Move(){
if len(this.queue1) == 0{
//交换,queue1置为queue2,queue2置为空
this.queue1,this.queue2 = this.queue2,this.queue1
}else{
//queue1元素从头开始一个一个追加到queue2中
this.queue2 = append(this.queue2,this.queue1[0])
this.queue1 = this.queue1[1:] //去除第一个元素
this.Move() //重复
}
}

func (this *MyStack) Pop() int {
val := this.queue1[0]
this.queue1 = this.queue1[1:] //去除第一个元素
return val

}


func (this *MyStack) Top() int {
return this.queue1[0] //直接返回
}


func (this *MyStack) Empty() bool {
return len(this.queue1) == 0
}


/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/
```

使用一个队列实现
```go
type MyStack struct {
queue []int//创建一个队列
Expand Down

0 comments on commit 5561706

Please sign in to comment.