《剑指Offer》09-用两个栈实现队列

理解题意

本题最难的就是理解题啥意思:

本来理解的就对,但看了一眼解析直接跑到了外太空;

咱们来看题中给的示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

输入的两行,个数相同,一一对应,我这里误解为这事两个栈了;其实不然,此题为两个栈来模拟的一个逻辑队列,很好判断,抓住一点,队列内的元素应该一致,一会是字符串,一会是数,可能性很小,所以可以很快推出这俩列表是给了操作队列的操作和操作数,以示例1为例:

  1. CQueue []:创建空队列;--> null (CQueue无返回值)
  2. appendTail 3:队列插入3;--> null (AppendTail无返回值)
  3. deleteHead []:出队;--> 3(出队:返回所出队元素)
  4. deleteHead []:出队;--> -1 (出队:但队列此时为空)

双栈实现队列过程详情:

栈:先进后出,队列:先进先出;

所以可以设置stack1为入队栈,stack2为出队栈;

IMG_CCE2F6B0D4DF-1

stack2中有元素一定是先于stack1中元素的,所有stack2中有元素就直接出栈即为出队;

算法实现

代码详情:Coding-Interviews/09-用两个栈实现队列-参考学习 at main · kp-hang/Coding-Interviews (github.com)

type CQueue struct { // 结构体定义;
	stack1 *list.List
	stack2 *list.List
}

func Constructor() CQueue { // 结构体实例化,最常用;
	return CQueue{
		stack1: list.New(),
		stack2: list.New(),
	}
}

func (this *CQueue) AppendTail(value int) {
	this.stack1.PushBack(value) // 	尾插;
}

func (this *CQueue) DeleteHead() int {
	if this.stack2.Len() == 0 { //出栈为空,就从入栈里转移元素;
		for this.stack1.Len() > 0 {
			this.stack2.PushBack(this.stack1.Remove(this.stack1.Back()))
		}
	}
	if this.stack2.Len() != 0 {
		e := this.stack2.Back()
		this.stack2.Remove(e)
		return e.Value.(int)
	}
	return -1
}

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

值得注意的是认真阅读标准库函数的说明,比如:

func (*list.List).Remove(e *list.Element) interface{}
(list.List).Remove on pkg.go.dev
Remove removes e from l if e is an element of list l. It returns the element value e.Value. The element must not be nil.
posted @ 2022-01-20 22:50  KpHang  阅读(43)  评论(0编辑  收藏  举报