如何用栈结构实现队列结构:用两个栈拼队列结构
package com.harrison.class02;
import java.util.Stack;
public class Code07_TwoStacksImplementQueue {
public static class TwoStacksToQueue{
public Stack<Integer> pushStack;
public Stack<Integer> popStack;
public TwoStacksToQueue() {
pushStack=new Stack<Integer>();
popStack=new Stack<Integer>();
}
public void pushToPop() {
if(popStack.isEmpty()) {
while(!pushStack.isEmpty()) {
popStack.push(pushStack.pop());
}
}
}
public void add(int pushInt) {
pushStack.push(pushInt);
pushToPop();
}
public int poll() {
if(pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("队列空了!");
}
pushToPop();
return popStack.pop();
}
public int peek() {
if(pushStack.isEmpty() && popStack.isEmpty()) {
throw new RuntimeException("队列空了!");
}
pushToPop();
return popStack.peek();
}
}
public static void main(String[] args) {
TwoStacksToQueue test=new TwoStacksToQueue();
test.add(1);
test.add(2);
test.add(3);
System.out.println(test.peek());
System.out.println(test.poll());
System.out.println(test.peek());
System.out.println(test.poll());
System.out.println(test.peek());
System.out.println(test.poll());
}
}