本文共 1271 字,大约阅读时间需要 4 分钟。
用两个栈实现一个队列:
队列是先进先出,而栈是先进后出;为了能使队列移除头部元素,就需要保证栈顶元素是最先进入的元素:
复杂度:
golang中没有默认的stack库,使用切片模拟(只在尾部插入与删除):
队列定义:
type CQueue struct { Input []int Output []int}
在使用队列前,需要先通过Constructor构造出队列:
func Constructor() CQueue { //instance := new(CQueue) instance := CQueue{ Input: make([]int, 0), Output: make([]int, 0), } return instance}func (this *CQueue) AppendTail(value int) { this.Input = append(this.Input, value)}func (this *CQueue) DeleteHead() int { if len(this.Output) == 0 { for index := len(this.Input) - 1; index >= 0; index-- { this.Output = append(this.Output, this.Input[index]) } this.Input = this.Input[:0] } size := len(this.Output) if size == 0 { return -1 } result := this.Output[size-1] this.Output = this.Output[:size-1] return result}func TestQueue() { qu := Constructor() qu.AppendTail(1) qu.AppendTail(2) fmt.Println(qu.DeleteHead())}
转载地址:http://qwilf.baihongyu.com/