面试题 7:用两个栈实现队列
tag: stack queue 栈与队列的互转
leetcode: 232. 用栈实现队列
public class MyQueue {
// 使用两个栈,利用栈的后进先出,实现队列的先进先出
Stack<Integer> inQueue;
// 出栈队列
Stack<Integer> outQueue;
// 只有构造类的时候才创建对象
public MyQueue() {
this.inQueue = new Stack<>();
this.outQueue = new Stack<>();
}
// 压入元素
public void push(int x) {
// 入队,仅放入入队队列
inQueue.push(x);
}
// 弹出,先看出队队列有没有,要短路阶段,减少判断
// Removes the object at the top of this stack and returns that object as the value of this function
public int pop() {
// 所有复杂数据结构在使用前都要进行非空判断
if (!outQueue.isEmpty()) {
return outQueue.pop();
}
if (!inQueue.isEmpty()) {
// 对队列等的循环,最好要while
while (!inQueue.isEmpty()) {
outQueue.push(inQueue.pop());
}
return outQueue.pop();
}
// 都为空,返回
return -1;
}
// Looks at the object at the top of this stack without removing it from the stack
public int peek() {
// peek不是弹出,检视
if (!outQueue.isEmpty()) {
return outQueue.peek();
}
if (!inQueue.isEmpty()) {
// 对队列等的循环,最好要while
while (!inQueue.isEmpty()) {
outQueue.push(inQueue.pop());
}
return outQueue.peek();
}
return -1;
}
public boolean empty() {
return outQueue.isEmpty() && inQueue.isEmpty();
}
}

被折叠的 条评论
为什么被折叠?



