232. 用栈实现队列

type MyQueue struct {
in, out []int
}
func Constructor() MyQueue {
return MyQueue{}
}
func (this *MyQueue) Push(x int) {
this.in = append(this.in, x)
}
// 栈1转到栈2
func (this *MyQueue) convent() {
for len(this.in)>0 {
this.out = append(this.out, this.in[len(this.in)-1])
this.in = this.in[:len(this.in)-1]
}
}
func (this *MyQueue) Pop() int {
if len(this.out) == 0 { // 栈2为空
this.convent()
}
top := this.out[len(this.out)-1]
this.out = this.out[:len(this.out)-1]
return top
}
func (this *MyQueue) Peek() int {
if len(this.out) == 0 {
this.convent()
}
return this.out[len(this.out)-1]
}
func (this *MyQueue) Empty() bool {
return len(this.in) == 0 && len(this.out) == 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();
*/
posted @   gdut17_2  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示