你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

golang力扣leetcode 232. 用栈实现队列

2021/12/10 3:27:52

232.用栈实现队列

  • 232.用栈实现队列
  • 题解
  • 代码

232.用栈实现队列

232.用栈实现队列

题解

大水题

代码

package main

type MyQueue struct {
	stack []int
	back  []int
}

func Constructor() MyQueue {
	return MyQueue{
		stack: make([]int, 0), //push
		back:  make([]int, 0), //pop
	}
}

func (this *MyQueue) Push(x int) {
	for len(this.back) != 0 {
		val := this.back[(len(this.back) - 1)]
		this.back = this.back[:len(this.back)-1]
		this.stack = append(this.stack, val)
	}
	this.stack = append(this.stack, x)
}

func (this *MyQueue) Pop() int {
	for len(this.stack) != 0 {
		val := this.stack[len(this.stack)-1]
		this.stack = this.stack[:len(this.stack)-1]
		this.back = append(this.back, val)
	}
	val := this.back[len(this.back)-1]
	this.back = this.back[:len(this.back)-1]
	return val
}

func (this *MyQueue) Peek() int {
	for len(this.stack) != 0 {
		val := this.stack[len(this.stack)-1]
		this.stack = this.stack[:len(this.stack)-1]
		this.back = append(this.back, val)
	}
	val := this.back[len(this.back)-1]
	return val
}

func (this *MyQueue) Empty() bool {
	return len(this.stack) == 0 && len(this.back) == 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();
 */