双向链表(Java实现)带泛型
package whh.sort;
public class LinkedList<T> {
private int key;
private LinkedList<T>head;
private LinkedList<T>tail;
private LinkedList<T>next;
private LinkedList<T>pre;
private T data;
private int len;
public LinkedList(int key,T data) {
this.data = data;
this.key = key;
head = this;
tail = head;
len++;
}
public void add(LinkedList<T> node){
tail.next = node;
node.pre = tail;
tail = node;
len++;
}
public void del(int key){
if(head.key == key){
head = head.next;
head.pre = null;
len--;
}else if(tail.key == key){
tail = tail.pre;
tail.next = null;
len--;
}else{
LinkedList<T> current = get(key);
if(current == null){
System.out.println("删除失败");
return;
}
current.pre.next = current.next;
current.next.pre=current.pre;
current = null;
len--;
}
}
public LinkedList<T> get(int key){
if(head.key == key){
return head;
}else if(tail.key == key){
return tail;
}else{
LinkedList<T> temp = head;
while(temp!=null){
if(temp.key == key){
break;
}
temp = temp.next;
}
return temp;
}
}
public void show(){
System.out.println(head);
if(head.next!=null){
head.next.show();
}
}
public static void main(String[] args) {
LinkedList<Integer> l = new LinkedList<Integer>(1, 1);
for (int i = 2; i < 10; i++) {
l.add(new LinkedList<Integer>(i, i));
}
l.show();
System.out.println("头结点");
System.out.println(l.head);
System.out.println("尾巴结点");
System.out.println(l.tail);
System.out.println("*************");
l.del(1);
l.del(10);
System.out.println(l.head.pre);
l.show();
System.out.println(l.len);
System.out.println(l.get(7));
System.out.println(l.get(4).pre);
System.out.println(l.get(2).next);
}
@Override
public String toString() {
return "LinkedList [key=" + key + ", data=" + data + "]";
}
}