1. 程式人生 > >線性結構(二)----單鏈表

線性結構(二)----單鏈表

  單鏈表:

    通過class建立物件,為物件給予特殊屬性成為節點,多個節點形成連結串列

 

 

 1 public class Node {
 2     
 3     //節點內容
 4     int data;
 5     //下一個節點
 6     Node next;
 7     
 8     public Node(int data){
 9         this.data=data;
10     }
11     
12     //為節點追加節點
13     public Node append(Node node){
14         //
當天節點 15 Node currentNode=this; 16 //向後查詢有沒有節點 17 while(true){ 18 //取出下一個節點 19 Node nextNode=currentNode.next; 20 //如果下一個節點為null,當前節點已經是最後一個節點 21 if(nextNode==null){ 22 break; 23 } 24 //賦給當前節點 25 currentNode=nextNode;
26 } 27 //把需要追加的節點追加為找到,currentNode為找到需要追加的節點 28 currentNode.next=node; 29 return this; 30 } 31 32 //插入一個節點 33 public void after(Node node){ 34 //取出下一個節點,作為新節點的下一個節點 35 Node nextnext=next; 36 //把這個節點的下一個節點設為新節點 37 this.next=node;
38 // 39 node.next=nextnext; 40 41 } 42 43 //顯示所有節點資訊 44 public void show(){ 45 Node currentNode=this; 46 while(true){ 47 System.out.print(currentNode.data+" "); 48 //取出下一個節點 49 currentNode=currentNode.next; 50 //如果是最後一個節點 51 if(currentNode==null){ 52 break; 53 } 54 } 55 } 56 57 //刪除下一個節點 58 public void removeNext(){ 59 //先取出下下一個節點 60 Node newnode= next.next(); 61 //替換下一個節點 62 this.next=newnode; 63 } 64 65 //獲取下一個節點 66 public Node next(){ 67 return this.next; 68 } 69 70 //獲取節點中資料 71 public int getData(){ 72 return this.data; 73 } 74 75 //當前節點是否是最後一個節點 76 public boolean isLast(){ 77 return next==null; 78 } 79 80 }