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 @ 2024-06-07 16:26  gdut17_2  阅读(17)  评论(0)    收藏  举报