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 +