单向链表的Java实现

一、链表的简单实现

 1 package test01;
 2 
 3 /*
 4  * 单向链表的简单实现
 5  * */
 6 
 7 class Node{
 8     private String data;
 9     private Node next;
10     public Node(String data){
11         this.data = data;
12     }
13     public String getData() {
14         return data;
15     }
16     public void setData(String data) {
17         this.data = data;
18     }
19     public Node getNext() {
20         return next;
21     }
22     public void setNext(Node next) {
23         this.next = next;
24     }
25 }
26 
27 public class LianBiao {
28 
29     public static void main(String[] args) {
30         Node n0 = new Node("A");
31         Node n1 = new Node("B");
32         Node n2 = new Node("C");
33         n0.setNext(n1);
34         n1.setNext(n2);
35         Print(n0);
36     }
37 
38     private static void Print(Node n0) {
39         System.out.println(n0.getData());
40         if(n0.getNext() != null){
41             Print(n0.getNext());
42         }
43         
44     }
45 
46 }

二、链表的正宗实现

 1 package test02;
 2 
 3 /*
 4  * 单向链表的正宗实现
 5  * */
 6 
 7 class Link{
 8     class Node{
 9         private String data;
10         private Node next;
11         public Node(String data){
12             this.data = data;
13         }
14         public void addNode(Node newNode){
15             if(this.next == null){
16                 this.next = newNode;
17             }else{
18                 this.next.addNode(newNode);
19             }
20         }
21         public void printNode(){
22             System.out.println(this.data);
23             if(this.next != null){
24                 this.next.printNode();
25             }
26         }
27     }
28     Node root;
29     public void add(String data){
30         Node newNode = new Node(data);//第一步就是生成节点,接下来就可以参考链表的简单实现方法
31         if(this.root == null){
32             this.root = newNode;
33         }else{
34             this.root.addNode(newNode);
35         }
36     }
37     public void printnode(){
38         this.root.printNode();
39     }
40 }
41 
42 public class LianBiao01 {
43 
44     public static void main(String[] args) {
45         Link l = new Link();
46         l.add("ROOT");
47         l.add("A");
48         l.add("B");
49         l.add("C");
50         l.printnode();
51     }
52 }

 

posted @ 2017-08-23 09:03  XuGuobao  阅读(193)  评论(0编辑  收藏  举报