用两个栈实现队列

63 阅读1分钟

image.png

代码:

  1. in按顺序进栈
  2. out接受in按顺序弹栈的值
  3. 这时候,out中的值,按顺序弹栈就是,in进栈时的顺序
  4. 所以模拟队列时,如果out不为0,直接弹栈out就行
  5. 如果为0,则将in中的数据弹栈到out,再弹栈out
  6. 当然如果都为0,则return -1,意味着报错
type CQueue struct {
    in, out []int
}


func Constructor() CQueue {
    return CQueue{}
}


func (this *CQueue) AppendTail(value int)  {
    this.in = append(this.in, value)
}


func (this *CQueue) DeleteHead() int {
    if len(this.out) == 0 {
        if len(this.in) == 0 {
            return -1
        }
        this.in2out()
    }
    value := this.out[len(this.out)-1]
    this.out = this.out[:len(this.out)-1]
    return value 
}

func (this *CQueue) in2out() {
    for len(this.in) > 0 {
        this.out = append(this.out, this.in[len(this.in)-1])
        this.in = this.in[:len(this.in)-1]
    }
}


/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */