题目链接
【Leetcode】232. 用栈实现队列
代码
type MyQueue struct {
A []int
B []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
}