栈和队列
栈和队列
栈:数据先进后出,犹如弹匣
队列:数据先进先出,好似排队
双向链表实现 栈和队列
static class DoubleNode<T>{
T value;
DoubleNode last;
DoubleNode next;
public DoubleNode(T value) {
this.value = value;
}
}
public static class DoubleEndsQueue<T> {
DoubleNode<T> pre=null;
DoubleNode<T> tail=null;
public void addHead(T t){
DoubleNode node=new DoubleNode(t);
if (pre==null){
pre=node;
tail=node;
}else{
node.next=pre;
pre.last=node;
pre=node;
}
}
public void addTail(T t){
DoubleNode node=new DoubleNode(t);
if (pre==null){
pre=node;
tail=node;
}else{
tail.next=node;
node.last=tail;
tail=node;
}
}
public T removeHead(){
if (pre==null)return null;
DoubleNode<T> node = pre.next;
T t=pre.value;
if (tail==pre){
tail=null;
pre=null;
return t;
}
pre.next=null;
node.last=null;
pre=node;
return t;
}
public T removeTail(){
if (tail==null)return null;
DoubleNode<T> node = tail.last;
T t=tail.value;
if (tail==pre){
tail=null;
pre=null;