使用栈实现队列的下列操作:
- push(x) -- 将一个元素放入队列的尾部。
- pop() -- 从队列首部移除元素。
- peek() -- 返回队列首部的元素。
- empty() -- 返回队列是否为空。
MyQueue queue = new MyQueue();queue.push(1);queue.push(2); queue.peek(); // 返回 1queue.pop(); // 返回 1queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
栈的思想是先进后出,那我们怎么实现利用栈来实现先进先出的队列呢?
我们先来看张图
进入队列的顺序为1》2》3,那我们就把这三个元素放进input栈中,再把input栈中的元素放进output栈里,那么我们可以看见,我们从output读取的数据就是1》2》3了
那么我们一个一个方法来看:
push:对于push方法,我们只需要把元素放进input栈中即可
pop:对于pop方法,我们要从output栈中获取栈顶元素,如果output栈中为空,那么我们就要从input栈中把元素都放进output栈中,再从output栈中取出栈顶元素即可,如果两个栈都是空的,那就啥事都不干
peek:对于peek方法,与pop方法基本是一样,只是读取而已,不用去除元素
empty:只需要判断input栈和output栈的容量合起来是不是不为空即可
核心代码:
package maintype MyQueue struct { InputStack []int //输入栈 OutputStack []int //输出栈}/** Initialize your data structure here. */func Constructor() MyQueue { queue := MyQueue{[]int{}, []int{}} return queue}/** Push element x to the back of queue. */func (this *MyQueue) Push(x int) { this.InputStack = append(this.InputStack, x)}/** Removes the element from in front of queue and returns that element. */func (this *MyQueue) Pop() int { //当输出栈不为空的,那就直接取出输出栈顶元素 if len(this.OutputStack) != 0 { x := this.OutputStack[len(this.OutputStack)-1] this.OutputStack = this.OutputStack[:len(this.OutputStack)-1] return x } //如果输出栈为空,但是输入栈不为空,那就把输入栈的元素放进输出栈,并去除栈顶元素 if len(this.InputStack) != 0 { for i := len(this.InputStack); i > 0; i-- { this.OutputStack = append(this.OutputStack, this.InputStack[i-1]) this.InputStack = this.InputStack[:len(this.InputStack)-1] } x := this.OutputStack[len(this.OutputStack)-1] this.OutputStack = this.OutputStack[:len(this.OutputStack)-1] return x } return 0 //两个栈都是空的}/** Get the front element. */func (this *MyQueue) Peek() int { if len(this.OutputStack) != 0 { return this.OutputStack[len(this.OutputStack)-1] } if len(this.InputStack) != 0 { for i := len(this.InputStack); i > 0; i-- { this.OutputStack = append(this.OutputStack, this.InputStack[i-1]) this.InputStack = this.InputStack[:len(this.InputStack)-1] } return this.OutputStack[len(this.OutputStack)-1] } return 0}/** Returns whether the queue is empty. */func (this *MyQueue) Empty() bool { if len(this.InputStack)+len(this.OutputStack) == 0 { return true } return false}func main() { queue := Constructor() queue.Push(1) queue.Push(2) _ = queue.Peek() _ = queue.Pop() _ = queue.Empty()}