前面已經介紹了java如何實現順序鏈表:http://www.cnblogs.com/lixiaolun/p/4643664.html
接下來,我們開始學習java實現單鏈表。
單鏈表類
package linklist; public class LinkList { class Element { public Object value=null; private Element next=null; } private Element header = null;//頭結點 /** * 初始化鏈表 * */ void initList() { header = new Element(); header.value=null; header.next=null; } /** * 插入鏈表 * */ void insertList(Object o) { Element e=new Element(); e.value=o; if(header.next==null)//第一次插入元素 { header.next=e; }else//不是第一次插入元素 { //temp引用在棧中,temp和header引用都指向堆中的initList()中new的Element對象 Element temp = header; while(temp.next!=null)//尋找最后一個元素 { temp=temp.next; } temp.next=e; } } /** * 刪除鏈表中第i個元素 * */ void deletelist(Object o) { Element temp =header; while(temp.next!=null) { //判斷temp當前指向的結點的下一個結點是否是要刪除的結點 if(temp.next.value.equals(o)) { temp.next=temp.next.next;//刪除結點 }else { temp=temp.next;//temp“指針”后移 } } } /** * 獲取鏈表的第i個位置的元素 * */ Element getElement(int i) { if(i<=0 || i>size()) { System.out.println("獲取鏈表的位置有誤!返回null"); return null; } else { int count =0; Element element = new Element(); Element temp = header; while(temp.next!=null) { count++; if(count==i) { element.value=temp.next.value; } temp=temp.next; } return element; } } /** * 鏈表長度 * */ int size() { Element temp = header; int size=0; while(temp.next!=null) { size++; temp=temp.next; } return size; } /** * 判斷鏈表中是否存在某元素 * */ Boolean isContain(Object o) { Element temp =header; while(temp.next!=null) { if(temp.next.value.equals(o)) { return true; } temp=temp.next; } return false; } /** * 打印鏈表 * */ void print() { System.out.print("打印鏈表:"); Element temp =header; while(temp.next!=null) { temp=temp.next; System.out.print(temp.value+"\t"); } System.out.println(); } }
測試類
package linklist; public class LinkListMain { public static void main(String[] args) { LinkList lList = new LinkList(); lList.initList(); lList.insertList(1); lList.insertList(2); lList.insertList(3); lList.insertList(4); lList.insertList(5); lList.print(); lList.deletelist(2); lList.print(); System.out.println("鏈表長度:"+lList.size()); System.out.println("第1個元素值為:"+lList.getElement(1).value); System.out.println("第2個元素值為:"+lList.getElement(2).value); System.out.println("第3個元素值為:"+lList.getElement(3).value); System.out.println("第4個元素值為:"+lList.getElement(4).value); System.out.println(lList.isContain(2)); System.out.println(lList.isContain(6)); System.out.println(lList.isContain(5)); } }