用两个栈实现队列,实现两个函数appendtail和deleteHead,分别完成在队尾插入节点和队头删除节点的功能
Java语言实现
import java.util.Stack;
/**
* 用两个栈实现队列
* 用两个栈实现队列,分别完成队头删节点,队尾加节点
*/
public class problem5 <T>{
private Stack<T> stack1 = new Stack<T>();
private Stack<T> stack2 = new Stack<T>();
public void appendTail( T t){
stack1.push(t);
for (T t1 : stack1) {
System.out.println("stack1:"+t1);
}
}
public T deleteHead () {
if(stack2.isEmpty()){
if (!stack1.isEmpty()){
stack2.push(stack1.pop());
for (T s :stack2) {
System.out.println("stack2:"+s);
}
}else {
try {
throw new Exception("队列为空,不能删除") ;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return stack2.pop();
}
public static void main(String[] args) {
problem5<String> P5 = new problem5<>();
P7.appendTail("1");
P7.appendTail("2");
P7.appendTail("3");
P7.deleteHead();
}
}