class GenericLink<T>{
class Entry{//节点
T data;
Entry next;
public Entry(){
data = null;
next = null;
}
public Entry(T val){
data = val;
next = null;
}
}
Entry head = new Entry();
public void insertHead(T val){//头插法
Entry cur = new Entry(val);
cur.next = head.next;
head.next = cur;
}
public void insertTail(T val){//尾插法
Entry entry = new Entry(val);
Entry cur = head;
while(cur.next != null){
cur = cur.next;
}
cur.next = entry;
}
public void delete(T val){//删除值为val的
Entry cur1 = head.next;
Entry cur2 = head;
while(cur1 != null){
if(cur1.data == val){
cur2.next = cur1.next;
cur1 = cur2.next;
}else{
cur1 = cur1.next;
cur2 = cur2.next;
}
}
}
public void show(){//打印链表
Entry cur = head.next;
while(cur != null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
}
用泛型实现链表
最新推荐文章于 2022-08-31 13:47:05 发布