LeetCode:232. 用栈实现队列
【题目描述】
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
【输入输出样例】
输入: ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 1, 1, false] 解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
【提示】
1 <= x <= 9
- 最多调用
100
次push
、pop
、peek
和empty
- 假设所有操作都是有效的 (例如,一个空的队列不会调用
pop
或者peek
操作)
【思路分析】
栈遵循先进后出原则,队列遵循先进先出原则,栈中想要获取栈底元素只能先依次弹出栈顶元素,如果把栈中元素的顺序反转,就可以实现直接弹出栈顶(原栈底)元素。
所以可以使用两个栈,stack1用来压入元素,在合适的时机把stack1中的元素依次弹出同时压入stack2中,实现stack2中元素是stack1中的倒序。
此时,这两个栈就可以模拟队列的基本操作。
【代码实现】
class MyQueue {
//stack1用于元素进队
Deque<Integer> stack1;
//stack2中元素是stack1中的倒序
Deque<Integer> stack2;
public MyQueue() {
stack1 = new LinkedList<>();
stack2 = new LinkedList<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (!stack2.isEmpty())
return stack2.pop();
else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
public boolean empty() {
if (stack1.isEmpty() && stack2.isEmpty())
return true;
else return false;
}
}