From b87d3266b6604aaaac139b03f7e28e3943d92f5f Mon Sep 17 00:00:00 2001 From: CJ-cooper6 <71270517+CJ-cooper6@users.noreply.github.com> Date: Sun, 31 Oct 2021 16:37:04 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0225.=20=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88=20=20Go=20=E4=B8=A4?= =?UTF-8?q?=E4=B8=AA=E9=98=9F=E5=88=97=E5=AE=9E=E7=8E=B0=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加225. 用队列实现栈 Go 两个队列实现版本 --- problems/0225.用队列实现栈.md | 66 +++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index d9819626..c3a6ef8e 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -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//创建一个队列