631
京東網上商城
Java麵向對象基礎--實現單向鏈表
1、設計節點類
以string為數據保存內容,還必須有一個屬性保存下一個節點的引用地址。
class Node{ // 定義節點類 private String data ; // 保存節點內容 private Node next ; // 表示保存下一個節點 public Node(String data){ // 通過構造設置節點內容 this.data = data ; // 設置內容 } public void setNext(Node next){ this.next = next ; // 設置下一個節點 } public Node getNext(){ // 取得下一個節點 return this.next ; } public String getData(){ return this.data ; // 取得節點的內容 } };
2、測試節點類
class Node{ // 定義節點類 private String data ; // 保存節點內容 private Node next ; // 表示保存下一個節點 public Node(String data){ // 通過構造設置節點內容 this.data = data ; // 設置內容 } public void setNext(Node next){ this.next = next ; // 設置下一個節點 } public Node getNext(){ // 取得下一個節點 return this.next ; } public String getData(){ return this.data ; // 取得節點的內容 } }; public class LinkDemo01{ public static void main(String args[]){ Node root = new Node("火車頭") ; // 定義根節點 Node n1 = new Node("車廂-A") ; // 定義第一個車廂(第一個節點) Node n2 = new Node("車廂-B") ; // 定義第二個車廂(第二個節點) Node n3 = new Node("車廂-C") ; // 定義第三個車廂(第三個節點) root.setNext(n1) ; // 設置火車頭的下一個節點是第一個車廂A n1.setNext(n2) ; // 設置第一個車廂的下一個節點是第二個車廂 n2.setNext(n3) ; // 設置第二個車廂的下一個節點是第三個車廂 n3.setNext(null); printNode(root) ; // 從頭開始輸出 } //遞歸操作,進行輸出 public static void printNode(Node node){ // 輸出節點 System.out.print(node.getData() + "\t") ; // 輸出節點的內容 if(node.getNext()!=null){ // 判斷此節點是否存在下一個節點 printNode(node.getNext()) ; // 向下繼續輸出 } } };
最後更新:2017-04-03 15:21:46