Update0232.用栈实现队列 优化Go代码实现

使用切片模拟栈的实现,即 MyStack
This commit is contained in:
cherrypicker
2023-12-22 10:02:23 +08:00
parent d9dab0d2b9
commit 1fbe055325

View File

@ -235,52 +235,77 @@ class MyQueue:
### Go
```Go
type MyQueue struct {
stackIn []int //输入栈
stackOut []int //输出栈
// 通过切片实现一个栈
// 由于只是辅助实现算法题目,因此不做异常情况处理
type MyStack []int
func (s *MyStack) Push(v int) {
*s = append(*s, v)
}
func (s *MyStack) Pop() int {
val := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return val
}
func (s *MyStack) Peek() int {
return (*s)[len(*s)-1]
}
func (s *MyStack) Size() int {
return len(*s)
}
func (s *MyStack) Empty() bool {
return s.Size() == 0
}
// ---------- 分界线 ----------
type MyQueue struct {
stackIn *MyStack
stackOut *MyStack
}
func Constructor() MyQueue {
return MyQueue{
stackIn: make([]int, 0),
stackOut: make([]int, 0),
return MyQueue {
stackIn: &MyStack{},
stackOut: &MyStack{},
}
}
// 往输入栈做push
func (this *MyQueue) Push(x int) {
this.stackIn = append(this.stackIn, x)
this.stackIn.Push(x)
}
// 在输出栈做poppop时如果输出栈数据为空需要将输入栈全部数据导入如果非空则可直接使用
func (this *MyQueue) Pop() int {
inLen, outLen := len(this.stackIn), len(this.stackOut)
if outLen == 0 {
if inLen == 0 {
return -1
}
for i := inLen - 1; i >= 0; i-- {
this.stackOut = append(this.stackOut, this.stackIn[i])
}
this.stackIn = []int{} //导出后清空
outLen = len(this.stackOut) //更新长度值
}
val := this.stackOut[outLen-1]
this.stackOut = this.stackOut[:outLen-1]
return val
this.fillStackOut()
return this.stackOut.Pop()
}
func (this *MyQueue) Peek() int {
val := this.Pop()
if val == -1 {
return -1
}
this.stackOut = append(this.stackOut, val)
return val
this.fillStackOut()
return this.stackOut.Peek()
}
func (this *MyQueue) Empty() bool {
return len(this.stackIn) == 0 && len(this.stackOut) == 0
return this.stackIn.Empty() && this.stackOut.Empty()
}
// fillStackOut 填充输出栈
func (this *MyQueue) fillStackOut() {
if this.stackOut.Empty() {
for !this.stackIn.Empty() {
val := this.stackIn.Pop()
this.stackOut.Push(val)
}
}
}
```