225. 用队列实现栈
题目
请你仅使用两个队列实现一个后入先出(LIFO
)的栈,并支持普通栈的全部四种操作(push
、top
、pop
和 empty
)。
实现 MyStack
类:
void push(int x)
将元素x
压入栈顶。int pop()
移除并返回栈顶元素。int top()
返回栈顶元素。boolean empty()
如果栈是空的,返回true
;否则,返回false
。
注意:
- 你只能使用队列的基本操作 —— 也就是
push to back
、peek/pop from front
、size
和is empty
这些操作。 - 你所使用的语言也许不支持队列。 你可以使用
list
(列表)或者deque
(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例
示例 1:
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
提示
1 <= x <= 9
- 最多调用
100
次push
、pop
、top
和empty
- 每次调用
pop
和top
都保证栈不为空
进阶
你能否仅用一个队列来实现栈。
解题思路
思路
这里进阶一下,只采用一个队列去模拟实现栈的功能。
主要重难点就是Pop
方法的实现:
- 每次
pop
的时候,将除队列尾部的那个元素全部pop
出来,在重新push
进入队列。 - 最后将队尾元素进行
pop
即可。
实现
package main
import "fmt"
type MyStack struct {
queue []int // 用数组实现一个队列的功能
}
func Constructor() MyStack {
return MyStack{
queue: make([]int, 0),
}
}
// 将元素 `x` 压入栈顶。
func (this *MyStack) Push(x int) {
// 直接把元素加入队列即可
this.queue = append(this.queue, x)
}
// 移除并返回栈顶元素
func (this *MyStack) Pop() int {
if len(this.queue) == 0 {
return 0
}
// 弹出除队尾元素的所有元素,并重新追加到队列中
n := len(this.queue) - 1
for n != 0 {
// 模拟队列头弹出元素,并且把队列头元素重新加入队列尾部
x := this.queue[0]
this.queue = this.queue[1:]
this.queue = append(this.queue, x)
n--
}
x := this.queue[0]
this.queue = this.queue[1:]
return x
}
// 返回栈顶元素
func (this *MyStack) Top() int {
x := this.Pop()
if x == 0 {
return x
}
this.Push(x)
return x
}
// 如果栈是空的,返回 `true` ;否则,返回 `false`
func (this *MyStack) Empty() bool {
if len(this.queue) != 0 {
return false
}
return true
}
func main() {
println("UseCase 1......")
stack := Constructor()
stack.Push(1)
stack.Push(2)
fmt.Printf("Peek: %v \n", stack.Top())
fmt.Printf("Pop: %v \n", stack.Pop())
fmt.Printf("Empty: %v \n", stack.Empty())
}