题目描述:用两个栈实现一个队列,实现队列的两个函数appendTail()和deleteHead(),分别在队列尾部插入节点,在头部删除节点。
import java.util.Stack; /** * Created by zj on 2017/3/11 0011. */ public class Queue<T> { private Stack<T> stack1 = new Stack<T>(); private Stack<T> stack2 = new Stack<T>(); public void appendTail(T t){ stack1.push(t); } public T deleteHead() throws Exception{ if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } if(stack2.isEmpty()){ throw new Exception("队列为空,不能删除"); } return stack2.pop(); } }