package List;public class List<T>{private static class Node<T> {T nodeValue;Node<T> next;Node(T nodeValue, Node<T> next){this.nodeValue=nodeValue;this.next =next;}Node(T nodeValue){this.nodeValue=nodeValue;this.next=null;}} private Node<T> head,p,q,m; public List() { head=null; } public boolean isEmpty()//判斷鏈表是否為空白 { if(head==null) { return true; } else { return false; } } public int Length()//返回當前鏈表中對象的個數 { int size=0; p=head; while(p!=null) { size++; p=p.next; } return size; } public void Add(T value) //在表尾添加某個對象 { q=head; p=new Node<T>(value); if(!isEmpty()) { while(q.next!=null) { q=q.next; } q.next=p; p.next=null; } else { p.next=head; head=p; } } public void AddHead(T value)//在表頭添加某個對象 { p=new Node<T>(value); p.next=head; head=p; } public void getData(int n)//取得某個位置的對象。構造main函數進行測試。 { int count=1; if(n>Length()) { System.out.println("對不起,你輸入的值已超出範圍"); } else { p=head; while(p!=null) { if(count==n) { System.out.println("第"+n+"個數值為:"+p.nodeValue); break; } count++; p=p.next; } } } public void Insert(int n,T value)//在某個位置插入對象 { int count=1; p=head; m=new Node<T>(value); while(p!=null) { if(count==n) { if(p!=head) { q.next=m; m.next=p; } else { m.next=head; head=m; } } count++; q=p; p=p.next; } } public void Delete(int n)//在某個位置刪除對象 { int count=1; p=head; while(p!=null) { if(count==n) { if(p!=head) { q.next=p.next; } else { head=head.next; } } count++; q=p; p=p.next; } } public void Delete_v(T x)//刪除鏈表中與x相同的元素 { p=head; int flag=0; while(p!=null) { if(p.nodeValue==x) { flag=1; if(p!=head) { q.next=p.next; } else { head=head.next; } } q=p; p=p.next; } if(flag==0) { System.out.println("對不起沒有找到元素:"+x); } } public void Traverse()//遍曆鏈表,列印出所有的元素 { p=head; System.out.print("遍曆鏈表:"); while(p!=null) { System.out.print(p.nodeValue); System.out.print(" "); p=p.next; } System.out.println(); } public static void main(String args[]) { List<Object> L = new List<Object>(); L.Add(4); if(!L.isEmpty()) { System.out.println("不空"); } else { System.out.println("空"); } L.Add(67); L.Add(55); L.AddHead(55); L.AddHead(3); for(int i=0;i<=L.Length();i++) { L.getData(i); } L.Traverse(); L.Insert(1,9); L.Delete(5); L.Delete(2); L.Delete_v(5); L.Delete_v(55); L.Traverse(); }}