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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例1:
输入:
[“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
分析
通过使用两个栈,一个输入栈和一个输出栈,在入队操作中,只需要将元素压入输入栈中即可,在出队和获取栈头元素操作中,将输入栈中全部的元素压入输出栈中,出队则对输出栈进行出栈操作并返回出栈元素,获取栈头元素操作则只需要获取最后出栈的元素,然后将全部元素再压入输入栈中即可。对于判断队列是否为空,只需要判断输入栈是否为空即可。
代码
class MyQueue {
private Stack<Integer> pus;
private Stack<Integer> pos;
private int stackSize;
public MyQueue() {
pus = new Stack<>();
pos = new Stack<>();
stackSize = 0;
}
public void push(int x) {
pus.push(x);
stackSize++;
}
public int pop() {
for(int i=0;i<stackSize;i++){
pos.push(pus.pop());
}
int ret = pos.pop();
while(!pos.isEmpty()){
pus.push(pos.pop());
}
stackSize--;
return ret;
}
public int peek() {
for(int i=0;i<stackSize-1;i++){
pos.push(pus.pop());
}
int ret=pus.pop();
pos.push(ret);
while(!pos.isEmpty()){
pus.push(pos.pop());
}
return ret;
}
public boolean empty() {
return pus.isEmpty();
}
}