單向鏈表的Java實現

來源:互聯網
上載者:User

標籤:lin   return   set   log   pre   logs   節點   test   void   

一、鏈表的簡單實現

 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 }

 

單向鏈表的Java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.