Loading

剑指 Offer 09. 用两个栈实现队列

剑指 Offer 09. 用两个栈实现队列

难度简单715收藏分享切换为英文接收动态反馈

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTaildeleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

示例 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead","deleteHead"]
[[],[3],[],[],[]]
输出:[null,null,3,-1,-1]

示例 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

提示:

  • 1 <= values <= 10000
  • 最多会对appendTail、deleteHead进行 10000 次调用
type CQueue struct {
    stackIn []int
    stackOut []int
}

func Constructor() CQueue {
    return CQueue{}

}

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

func (this *CQueue) DeleteHead() int {
    if len(this.stackOut)==0{
        //stackIn出栈
        if len(this.stackIn)==0{
            return -1
        }
        for i:=len(this.stackIn)-1;i>=0;i--{
            this.stackOut=append(this.stackOut,this.stackIn[i])
        }
        this.stackIn=[]int{}   
    }
    value := this.stackOut[len(this.stackOut)-1]
    this.stackOut=this.stackOut[:len(this.stackOut)-1]
    return value
}


/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */
posted @ 2023-03-14 10:59  suehoo  阅读(30)  评论(0编辑  收藏  举报