LeetCode-225.用队列实现栈

题目描述

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack类:

void push(int x) 将元素 x 压入栈顶。
int pop()移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true;否则,返回 false

注意:

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack类:

void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true;否则,返回 false

注意:

你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list(列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:

输入:

1
2
3
4
5
6
7
8
9
10
11
["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 次 pushpoptop empty
  • 每次调用 pop top都保证栈不为空

进阶:你能否仅用一个队列来实现栈。

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MyStack {
var queue = [Int]()
init() {

}

func push(_ x: Int) {
var length = queue.count
queue.append(x)
while length > 0 {
queue.append(queue.removeFirst())
length -= 1
}
}

func pop() -> Int {
return queue.removeFirst()
}

func top() -> Int {
return queue.first!
}

func empty() -> Bool {
return queue.isEmpty
}
}