今日任务:
● 理论基础
● 232.用栈实现队列
● 225. 用队列实现栈
1. 理论基础
- 栈
- 先进后出
- 队列
- 先进先出
2. 用栈实现队列
关联 leetcode 232.用栈实现队列
-
两个栈模拟队列【负负得正】
- 入栈
- 存储队列元素
- 出栈
- 将入栈元素全部存储到此处,实现顺序翻转
- 入栈
-
保证入栈元素全部倒出到出栈中
-
题解
type MyQueue struct { StackInput []int StackOutput []int } func Constructor() MyQueue { return MyQueue{ // 利用切片实现栈,先入后出,使用append追加元素,每次出最后一个元素 StackInput: make([]int, 0), StackOutput: make([]int, 0), } } // 写入只用写 入栈 即可 func (this *MyQueue) Push(x int) { this.StackInput = append(this.StackInput, x) } func (this *MyQueue) Pop() int { // 只有是 出栈 为空时,才将 入栈 全部内容写入 出栈 if len(this.StackOutput) == 0 { lastInputIdx := len(this.StackInput) - 1 // 可以拷贝一个入栈内容,删一个入栈数据,此处拷贝全部入栈后,清空 入栈 for i := lastInputIdx; i >= 0; i-- { this.StackOutput = append(this.StackOutput, this.StackInput[i]) } this.StackInput = make([]int, 0)// 拷贝完成后,清楚入栈 } lastOutputIdx := len(this.StackOutput) - 1 res := this.StackOutput[lastOutputIdx] this.StackOutput = this.StackOutput[:lastOutputIdx]//弹出元素 return res } func (this *MyQueue) Peek() int { res := this.Pop() this.StackOutput = append(this.StackOutput, res) return res } func (this *MyQueue) Empty() bool { return len(this.StackInput) == 0 && len(this.StackOutput) == 0 }
3. 用队列实现栈
关联 leetcode 225. 用队列实现栈
- 使用一个队列实现模拟栈
- 关键操作出栈
- 利用循环队列
- 每次先 pop size-1个元素后,将他们重新压入队列
- 将现在的第一个元素出队列,即是第一个出栈元素
- top()
- 返回队列尾部第一个元素即可
-
题解
type MyStack struct { Queue []int } func Constructor() MyStack { return MyStack{Queue: make([]int, 0)} } func (this *MyStack) Push(x int) { this.Queue = append(this.Queue, x) } func (this *MyStack) Pop() int { size := len(this.Queue) size -= 1 for size > 0 { val := this.Queue[0] this.Queue = this.Queue[1:] this.Push(val) size-- } res := this.Queue[0] this.Queue = this.Queue[1:] return res } func (this *MyStack) Top() int { return this.Queue[len(this.Queue)-1] } func (this *MyStack) Empty() bool { return len(this.Queue) == 0 }