剑指offer-09-用两个栈实现队列

剑指offer

Posted by kzdgt on Wednesday, March 2, 2022

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

09. 用两个栈实现队列

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

示例 1:

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

示例 2:

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

提示:

  • 1 <= values <= 10000
  • 最多会对 appendTaildeleteHead 进行 10000 次调用

编码模板

type CQueue struct {

}


func Constructor() CQueue {

}


func (this *CQueue) AppendTail(value int)  {

}


func (this *CQueue) DeleteHead() int {

}


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

我的解答

type CQueue struct {
	stackIn, stackOut *list.List
}

func Constructor() CQueue {
	return CQueue{
		stackIn:  list.New(),
		stackOut: list.New(),
	}
}

func (this *CQueue) AppendTail(value int) {

	this.stackIn.PushBack(value)

}

func (this *CQueue) DeleteHead() int {
	if this.stackOut.Len() > 0 {
		e := this.stackOut.Back()
		this.stackOut.Remove(e)
		return e.Value.(int)
	} else  {
		for this.stackIn.Len()>0 {
			this.stackOut.PushBack(this.stackIn.Remove(this.stackIn.Back()))
		}
		if this.stackOut.Len()==0 {
			return -1
		}else {
			e := this.stackOut.Back()
			this.stackOut.Remove(e)
			return e.Value.(int)
		}
	}
	
}

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

执行结果:

通过
显示详情
添加备注
执行用时:212 ms, 在所有 Go 提交中击败了28.89%的用户
内存消耗:8 MB, 在所有 Go 提交中击败了79.58%的用户
通过测试用例:55 / 55

「真诚赞赏,手留余香」

kzdgt Blog

真诚赞赏,手留余香

使用微信扫描二维码完成支付