代码简单,不在解释
package lesson01;
import java.util.Stack;
public class Code03_TwoStackQueue {
Stack<Integer> stackPush;
Stack<Integer> stackPop;
public Code03_TwoStackQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void push(int item) {
stackPush.push(item);
}
public int poll() throws Exception {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new Exception("Queue is empty!");
} else if (stackPop.isEmpty()) {
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek() throws Exception {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new Exception("Queue is empty!");
} else if (stackPop.isEmpty()) {
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
public static void main(String[] args) throws Exception {
Code03_TwoStackQueue queue = new Code03_TwoStackQueue();
for (int i = 0; i < 7; i++) {
queue.push(i);
}
for (int i = 0; i < 7; i++) {
System.out.print(" " + queue.poll());
}
}
}