LeetCode225-用队列实现栈

题目链接

英文链接:https://leetcode.com/problems/implement-stack-using-queues/

中文链接:https://leetcode-cn.com/problems/implement-stack-using-queues/

题目详述

使用队列实现栈的下列操作:

  • push(x) – 元素 x 入栈
  • pop() – 移除栈顶元素
  • top() – 获取栈顶元素
  • empty() – 返回栈是否为空

注意:

  • 你只能使用队列的基本操作– 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

题目详解

主要有两种实现方式,各种操作时间复杂度如下:

  • push: O(1), pop: O(n), peek: O(n)
  • push: O(n), pop: O(1), peek: O(1)

第一种实现:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class LeetCode_00225 {

// push: O(1), pop: O(n), peek: O(n)
class MyStack {

private Queue<Integer> queue;

/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}

/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = queue.size();
while (size-- > 1) {
queue.offer(queue.poll());
}
return queue.poll();
}

/** Get the top element. */
public int top() {
int size = queue.size();
while (size-- > 1) {
queue.offer(queue.poll());
}
int x = queue.poll();
queue.offer(x);
return x;
}

/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
}

第二种实现:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class LeetCode_00225 {

// push: O(n), pop: O(1), peek: O(1)
class MyStack {

private Queue<Integer> in;
private Queue<Integer> out;

/** Initialize your data structure here. */
public MyStack() {
in = new LinkedList<>();
out = new LinkedList<>();
}

/** Push element x onto stack. */
public void push(int x) {
in.offer(x);
while (!out.isEmpty()) {
in.offer(out.poll());
}
// 交换两者的角色(in 为空,out 按元素的逆序排列)
Queue tmp = in;
in = out;
out = tmp;
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return out.poll();
}

/** Get the top element. */
public int top() {
return out.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return out.isEmpty();
}
}
}