importjava.util.Stack;
public class Q7<T> {
/**
* 题目:用两个栈实现队列
* 题目说明:用两个栈实现一个队列。队列的声明如下:请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入和在对头删除结点的功能。
* 关键:实现的过程应该不是很复杂,不过大家要注意一点:只有在stack2完全出栈的情况下,才可以实现“入队”操作。
*/
private Stack<T> stack1=new Stack<T>();
private Stack<T> stack2=new Stack<T>();
public static void main(String[] args) throws Exception {
// TODOAuto-generated method stub
Q7<String> test = new Q7<String>();
test.appendTail("1");
test.appendTail("2");
test.appendTail("3");
test.appendTail("4");
test.deleteHead();
}
//通过stack1实现入队操作
public void appendTail(T t){
stack1.push(t);
}
//实现出队操作
public T deleteHead() throwsException{
//只有在stack2为空的情况下才能实现出对,否则输出的不再具有队列的“先进先出”的特点
if(stack2.isEmpty()){//stack2为空,且stack1不为空,实现队列操作
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()){//stack2为空,stack1为空,则队列为空
throw new Exception("队列为空");
}
return stack2.pop();
}
}