【Leetcode】232. 用栈实现队列
- 题目链接
- 代码
题目链接
【Leetcode】232. 用栈实现队列
代码
type MyQueue struct {A []intB []int
}func Constructor() MyQueue {return MyQueue{}
}func (this *MyQueue) Push(x int) {this.A = append(this.A, x)
}func (this *MyQueue) Pop() int {for len(this.A) > 0 {la := len(this.A)this.B = append(this.B, this.A[la-1])this.A = this.A[:la-1]}lb := len(this.B)ans := this.B[lb-1]this.B = this.B[:lb-1]for len(this.B) > 0 {lb = len(this.B)this.A = append(this.A, this.B[lb-1])this.B = this.B[:lb-1]}return ans
}func (this *MyQueue) Peek() int {for len(this.A) > 0 {la := len(this.A)this.B = append(this.B, this.A[la-1])this.A = this.A[:la-1]}lb := len(this.B)ans := this.B[lb-1]for len(this.B) > 0 {lb = len(this.B)this.A = append(this.A, this.B[lb-1])this.B = this.B[:lb-1]}return ans
}func (this *MyQueue) Empty() bool {return len(this.A) == 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();*/