问题出自:程序员小灰 - 如何用栈实现队列?
代码实现:
import java.util.*;
public class DummyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
DummyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void offer(int num) {
stack1.push(num);
}
public int peek() {
if(!stack2.isEmpty()) {
return stack2.peek();
}
dropStack();
return stack2.peek();
}
public int pull() {
if(!stack2.isEmpty()) {
return stack2.pop();
}
dropStack();
return stack2.pop();
}
public void dropStack() {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return;
}
public static void main(String[] args) {
DummyQueue queue = new DummyQueue();
queue.offer(1);
queue.offer(2);
queue.offer(3);
System.out.println(queue.peek());
System.out.println(queue.pull());
System.out.println(queue.pull());
queue.offer(4);
queue.offer(5);
System.out.println(queue.pull());
System.out.println(queue.pull());
System.out.println(queue.pull());
System.out.println(queue.pull());
}
}
测试结果: