使用栈实现队列
问题
这个题目说的是,你要使用栈来实现一个队列,需要实现队列中常用的 4 个函数。其中,push 函数往队尾加入一个元素;pop 函数把队首元素移除;peek 函数返回队首元素;empty 函数返回队列是否为空。另外你的实现不需要考虑异常操作情况,比如从一个空队列里 pop 元素。
代码
public class AlgoCasts {
public class MyQueue {
private Stack<Integer> in = new Stack<>(), out = new Stack<>();
private void transferIfEmpty() {
if (out.empty())
while (!in.empty())
out.push(in.pop());
}
public void push(int x) {
in.push(x);
}
public int pop() {
transferIfEmpty();
return out.pop();
}
public int peek() {
transferIfEmpty();
return out.peek();
}
public boolean empty() {
return in.empty() && out.empty();
}
}
}