Update 0232.用栈实现队列.md

about go版本
This commit is contained in:
FlySmile
2022-11-26 19:57:55 +08:00
committed by GitHub
parent 111016aef9
commit 067c25f616

View File

@ -231,56 +231,51 @@ class MyQueue:
Go Go
```Go ```Go
type MyQueue struct { type MyQueue struct {
stack []int stackIn []int //输入栈
back []int stackOut []int //输出栈
} }
/** Initialize your data structure here. */
func Constructor() MyQueue { func Constructor() MyQueue {
return MyQueue{ return MyQueue{
stack: make([]int, 0), stackIn: make([]int, 0),
back: make([]int, 0), stackOut: make([]int, 0),
} }
} }
/** Push element x to the back of queue. */ // 往输入栈做push
func (this *MyQueue) Push(x int) { func (this *MyQueue) Push(x int) {
for len(this.back) != 0 { this.stackIn = append(this.stackIn, x)
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. */ // 在输出栈做poppop时如果输出栈数据为空需要将输入栈全部数据导入如果非空则可直接使用
func (this *MyQueue) Pop() int { func (this *MyQueue) Pop() int {
for len(this.stack) != 0 { inLen, outLen := len(this.stackIn), len(this.stackOut)
val := this.stack[len(this.stack)-1] if outLen == 0 {
this.stack = this.stack[:len(this.stack)-1] if inLen == 0 {
this.back = append(this.back, val) return -1
} }
if len(this.back) == 0 { for i := inLen - 1; i >= 0; i-- {
return 0 this.stackOut = append(this.stackOut, this.stackIn[i])
} }
val := this.back[len(this.back)-1] this.stackIn = []int{} //导出后清空
this.back = this.back[:len(this.back)-1] outLen = len(this.stackOut) //更新长度值
}
val := this.stackOut[outLen-1]
this.stackOut = this.stackOut[:outLen-1]
return val return val
} }
/** Get the front element. */
func (this *MyQueue) Peek() int { func (this *MyQueue) Peek() int {
val := this.Pop() val := this.Pop()
if val == 0 { if val == -1 {
return 0 return -1
} }
this.back = append(this.back, val) this.stackOut = append(this.stackOut, val)
return val return val
} }
/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool { func (this *MyQueue) Empty() bool {
return len(this.stack) == 0 && len(this.back) == 0 return len(this.stackIn) == 0 && len(this.stackOut) == 0
} }
``` ```