导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-232.Implement Queue using Stacks

题目

Implement the following operations of a queue using stacks.

  • push(x) – Push element x to the back of queue.
  • pop() – Removes the element from in front of queue.
  • peek() – Get the front element.
  • empty() – Return whether the queue is empty.
    Notes:
  • You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

翻译

用栈来实现以下队列操作:

  • push(x) – 将元素x添加到队列尾部。
  • pop() – 将队列头部的元素移除。
  • peek() – 获取头部元素。
  • empty() – 返回队列是否为空。
    注意:
  • 只能使用栈的标准操作——只有push到头部、从头部peek/pop、size和is empty操作是允许的。
  • 根据语言不同,栈可能不被本地支持。可以使用链表或deque(双相队列)模拟一个栈,只要只使用栈的标准操作即可。
  • 可以认为所有的操作都是合法的(例如,不会对空队列进行pop或peek操作)。

设立两个栈,一个进栈,一个出栈。用两个栈模拟队列。

  • push:进队永远向进栈push;
  • pop:最早入队的元素一定在进栈的底端(出栈为空)或出栈的顶端(出栈不为空),所以出队操作时,只要返回出栈顶端元素(出栈不为空),或将进栈元素逐个压向出栈,再返回出栈顶端元素即可(出栈为空);
  • peek:操作与pop同理;
  • 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
class MyQueue {
private Stack<Integer> inStack = new Stack<Integer>();
private Stack<Integer> outStack = new Stack<Integer>();

// Push element x to the back of queue.
public void push(int x) {
inStack.push(x);
}

// Removes the element from in front of queue.
public void pop() {
if (!outStack.isEmpty())
outStack.pop();
else {
while (!inStack.isEmpty()) {
outStack.push(inStack.peek());
inStack.pop();
}
outStack.pop();
}
}

// Get the front element.
public int peek() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.peek());
inStack.pop();
}
}

return outStack.peek();
}

// Return whether the queue is empty.
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}