鏈表專題之一:建立鏈表,打印鏈表

package offer.linklist;

public class LinkList {
	// 頭結點
	public Node head;
	// 當前結點
	public Node current;

	// 添加結點
	public void add(int data) {
		// 判斷鏈表是否爲null
		if (head == null) {
			// 鏈表爲null,則表示鏈表中尚未結點
			// 頭結點爲新加入結點
			head = new Node(data);
			// 當前的結點變爲頭結點
			current = head;
		} else {
			// 鏈表不爲null,則當前結點的下一個結點爲新加入結點
			current.next = new Node(data);
			// 當前的結點變爲新加入的結點
			current = current.next;// 這一步是關鍵,別忘!!!!
		}
	}

	// 定義內部類-Node
	class Node {
		public int data;
		public Node next;

		public Node(int data) {
			this.data = data;
		}
	}

	// 打印鏈表
	public void printLinkList(LinkList list) {
		Node current = list.head;
		while (current != null) {
			System.out.print("--->" + current.data);
			current = current.next;
		}
	}

	// 測試鏈表
	public static void main(String[] args) {
		LinkList list = new LinkList();
		for (int i = 0; i < 5; i++) {
			list.add(i);
		}
		list.printLinkList(list);
	}
}
相關文章
相關標籤/搜索