ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

【Leetcode】232. 用栈实现队列

2026/8/12 1:38:38 拓冰建站 浏览量
【Leetcode】232. 用栈实现队列

【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();*/