package main
//思路用两个队列实现,利用栈先入后出着一特性,先让入第一个栈,然后讲第一个栈弹出同时入第二栈,此时就按队列实现先入先出了
type MyQueue struct {
//用数组模拟队列
QueueIn []int
QueueOut []int
}
func Constructor() MyQueue {
return MyQueue{QueueIn: []int{}, QueueOut: []int{}}
}
func (this *MyQueue) Push(x int) {
this.QueueIn = append(this.QueueIn, x)
}
func (this *MyQueue) Pop() int {
sizeIn := len(this.QueueIn)
sizeOut := len(this.QueueOut)
if sizeOut == 0 {
if sizeIn == 0 {
return -1
}
//把第一个栈弹出压入第二个栈
for i := sizeIn - 1; i >= 0; i-- {
this.QueueOut = append(this.QueueOut, this.QueueIn[i])
}
//把第一个栈清空
this.QueueIn = []int{}
sizeOut = len(this.QueueOut)
}
//每次弹出取最后一个值
value := this.QueueOut[sizeOut-1]
//将栈缩减
this.QueueOut = this.QueueOut[0 : sizeOut-1]
return value
}
func (this *MyQueue) Peek() int {
value := this.Pop()
if value == -1 {
return -1
}
//因为不是真正弹出,拿到值后再放回
this.QueueOut = append(this.QueueOut, value)
return value
}
func (this *MyQueue) Empty() bool {
return len(this.QueueIn) == 0 && len(this.QueueOut) == 0
}