天天看點

Java連結清單基本實作

class Link {
	
	private class Node {
		private Node next;//下一個節點
		private String data;//儲存資料

		public Node(String data) {//儲存資料構造方法
			this.data = data;
		}
		//添加新節點
		public void addNode(Node newNode) {
			if (this.next == null) {//如果此節點為null
				this.next = newNode;//新節點為此節點
			} else {//如果此節點不為null,遞歸調用。
				this.next.addNode(newNode);
			}
		}
		//輸出資料
		public void printNode() {
			System.out.println(this.data);//輸出現在節點的内容
			if (this.next != null) {//如果下一個節點不為null
				this.next.printNode();//輸出下一個節點的資料
			}
		}
	}
//==================以上為内部類==========================
	private Node root;//設定根節點 
//添加資料方法
	public void add(String data) {
		Node newNode = new Node(data);//先将資料放入一個節點中
		if (this.root == null) {//如果根節點為空
			this.root = newNode;//此newNode節點為根節點
		} else {
			this.root.addNode(newNode);//如果根節點存在,遞歸調用,把newNode設定為root的下一個節點
		}
	}
//輸出資料的方法
	public void print() {
		if (this.root != null) {//現在存在根節點
			root.printNode();//交給Node類輸出
		}
	}
}

public class NodeTest {
	public static void main(String[] args) throws Exception {
		Link link = new Link();
		link.add("大家好!");
		link.add("我是渣渣輝");
		link.add("歡迎來到貪玩攬月!");
		link.print();
	}
}