鏈表的代碼(共5頁)_第1頁
鏈表的代碼(共5頁)_第2頁
鏈表的代碼(共5頁)_第3頁
鏈表的代碼(共5頁)_第4頁
鏈表的代碼(共5頁)_第5頁
全文預覽已結束

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、精選優(yōu)質文檔-傾情為你奉上鏈表的代碼: /節(jié)點class node object data; node next;/指向下一個結點 import java.io.; public class list /用變量來實現表頭/ private node head=null; private node tail=null; private node pointer=null; private int length=0; public void deleteall() /清空整個鏈表/ head=null; tail=null; pointer=null; length=0; public void

2、reset() /鏈表復位,使第一個結點 成為當前結點/ pointer=null; public boolean isempty() /判斷鏈表是否為空/ return(length=0); public boolean isend() /判斷當前結點是否 為最后一個結點/ if(length=0) throw new java.lang.nullpointerexception(); else if(length=1) return true; else return(cursor()=tail); public object nextnode() /返回當前結點的下一個結點的值, 并使其

3、成為當前結點/ if(length=1) throw new java.util.nosuchelementexception(); else if(length=0) throw new java.lang.nullpointerexception(); else node temp=cursor(); pointer=temp; if(temp!=tail) return(temp.next.data); else throw new java.util.nosuchelementexception(); public object currentnode() /返回當前結點的值/ nod

4、e temp=cursor(); return temp.data; public void insert(object d) /在當前結點前插入一個結點, 并使其成為當前結點/ node e=new node(d); if(length=0) tail=e; head=e; else node temp=cursor(); e.next=temp; if(pointer=null) head=e; else pointer.next=e; length; public int size() /返回鏈表的大小/ return length; public object remove() /將當

5、前結點移出鏈表,下一個結點成為當前結點,如果移出的結點是最后一個結點,則第一個結點成為當前結點/ object temp; if(length=0) throw new java.util.nosuchelementexception(); else if(length=1) temp=head.data; deleteall(); else node cur=cursor(); temp=cur.data; if(cur=head) head=cur.next; else if(cur=tail) pointer.next=null; tail=pointer; reset(); else

6、pointer.next=cur.next; length; return temp; private node cursor() /返回當前結點的指針/ if(head=null) throw new java.lang.nullpointerexception(); else if(pointer=null) return head; else return pointer.next; public static void main(string args) /鏈表的簡單應用舉例/ list a=new list (); for(int i=1;i<=10;i) a.insert(n

7、ew integer(i); system.out.println(a.currentnode(); while(!a.isend() system.out.println(a.nextnode(); a.reset(); while(!a.isend() a.remove(); a.remove(); a.reset(); if(a.isempty() system.out.println(there is no node in list n); system.in.println(you can press return to quitn); try system.in.read(); /確保用戶看清程序運行結果 catch(ioexception e) class node /構成鏈表的結點定義/ object data; node next; node(object d) data=d; next=null; 讀者還可以根據實際需要定義新的方法來對鏈表進行操作。雙向鏈表可以用類似的方法實現只是結點的類增加了一個指向前趨結點的指針。 可

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論