0%

用栈实现队列

人类迷惑行为 x 2

创建两个栈 pushpop , 入队数据只进入 push , 出队只从 pop 出. 通过将 push 栈中的数据倒入 pop 栈中实现队列功能, 倒数据的过程中需满足两个条件:

  1. push 栈倒入 pop 栈之前, pop 栈必须为空
  2. push 栈中的数据一次性倒完
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
import java.util.Stack;

public class StackQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;

public StackQueue() {
pushStack = new Stack<>();
popStack = new Stack<>();
}

public void push(int newEle) {
stackTransfer(popStack, pushStack);
pushStack.push(newEle);
}

public int poll() {
stackTransfer(pushStack, popStack);
if (popStack.isEmpty())
throw new RuntimeException("Queue is empty");
return popStack.pop();
}

public int peek() {
stackTransfer(pushStack, popStack);
if (popStack.isEmpty())
throw new RuntimeException("Queue is empty");
return popStack.peek();
}

public boolean empty() {
return pushStack.isEmpty() && popStack.isEmpty();
}


public void stackTransfer(Stack stack1, Stack stack2) {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
}
}

例题: LeetCode #232

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

  • push(x) – 将一个元素放入队列的尾部。

  • pop() – 从队列首部移除元素。

  • peek() – 返回队列首部的元素。

  • empty() – 返回队列是否为空。

示例:

1
2
3
4
5
6
7
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

说明:

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

Java

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
44
45
46
class MyQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;

/** Initialize your data structure here. */
public MyQueue() {
pushStack = new Stack<>();
popStack = new Stack<>();
}

/** Push element x to the back of queue. */
public void push(int x) {
stackTransfer(popStack, pushStack);
pushStack.push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
stackTransfer(pushStack, popStack);
if (popStack.isEmpty())
throw new RuntimeException("Queue is empty");
return popStack.pop();
}

/** Get the front element. */
public int peek() {
stackTransfer(pushStack, popStack);
if (popStack.isEmpty())
throw new RuntimeException("Queue is empty");
return popStack.peek();
}

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

/** Put elements from stack1 into stack2. */
public void stackTransfer(Stack stack1, Stack stack2) {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
}
}

Python

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
44
45
46
47
class MyQueue:

def __init__(self):
"""
Initialize your data structure here.
"""
self.push_stack = []
self.pop_stack = []

def push(self, x):
"""
Push element x to the back of queue.
"""
self.stack_transfer(self.pop_stack, self.push_stack)
self.push_stack.append(x)

def pop(self):
"""
Removes the element from in front of queue and returns that element.
"""
self.stack_transfer(self.push_stack, self.pop_stack)
if len(self.pop_stack) == 0:
return None
return self.pop_stack.pop()

def peek(self):
"""
Get the front element.
"""
self.stack_transfer(self.push_stack, self.pop_stack)
if len(self.pop_stack) == 0:
return None
return self.pop_stack[-1]

def empty(self):
"""
Returns whether the queue is empty.
"""
return len(self.push_stack) == 0 and len(self.pop_stack) == 0

def stack_transfer(self, stack1, stack2):
"""
Put elements from stack1 into stack2.
"""
if len(stack2) == 0:
while len(stack1) != 0:
stack2.append(stack1.pop())