From b857e4bcbd6b2cf2ae9df3224ec218000735eedc Mon Sep 17 00:00:00 2001 From: QuinnDK <39618652+QuinnDK@users.noreply.github.com> Date: Tue, 18 May 2021 21:19:49 +0800 Subject: [PATCH] =?UTF-8?q?Update=200232.=E7=94=A8=E6=A0=88=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E9=98=9F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0232.用栈实现队列.md | 69 ++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index abdc363d..8bf646a4 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -190,6 +190,73 @@ Python: Go: +```Go +type MyQueue struct { + stack []int + back []int +} + +/** Initialize your data structure here. */ +func Constructor() MyQueue { + return MyQueue{ + stack: make([]int, 0), + back: make([]int, 0), + } +} + +/** Push element x to the back of queue. */ +func (this *MyQueue) Push(x int) { + for len(this.back) != 0 { + val := this.back[len(this.back)-1] + this.back = this.back[:len(this.back)-1] + this.stack = append(this.stack, val) + } + this.stack = append(this.stack, x) +} + +/** Removes the element from in front of queue and returns that element. */ +func (this *MyQueue) Pop() int { + for len(this.stack) != 0 { + val := this.stack[len(this.stack)-1] + this.stack = this.stack[:len(this.stack)-1] + this.back = append(this.back, val) + } + if len(this.back) == 0 { + return 0 + } + val := this.back[len(this.back)-1] + this.back = this.back[:len(this.back)-1] + return val +} + +/** Get the front element. */ +func (this *MyQueue) Peek() int { + for len(this.stack) != 0 { + val := this.stack[len(this.stack)-1] + this.stack = this.stack[:len(this.stack)-1] + this.back = append(this.back, val) + } + if len(this.back) == 0 { + return 0 + } + val := this.back[len(this.back)-1] + return val +} + +/** Returns whether the queue is empty. */ +func (this *MyQueue) Empty() bool { + return len(this.stack) == 0 && len(this.back) == 0 +} + +/** + * Your MyQueue object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * param_2 := obj.Pop(); + * param_3 := obj.Peek(); + * param_4 := obj.Empty(); + */ + ``` @@ -198,4 +265,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +