线性结构(二)----单链表

  单链表:

    通过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 }

猜你喜欢

转载自www.cnblogs.com/axu521/p/9966720.html