單鏈表
為什麼選擇單鏈表優點
單鏈表用於儲存相同型別的元素,其大小沒有限制向連結串列中插入元素速度快缺點
不能夠隨機訪問,必須從第一個元素開始每個指標需要額外的記憶體對於快取很不友好實現連結串列的第一個元素稱為頭(Head),在Java語言中使用Node類表示連結串列的節點,建立包含3個節點的連結串列。
public class SinglyLinkedList { Node head; // head of the list static class Node { int data; Node next; Node(int d) { data = d; next = null; } } public static void main(String[] args) { SinglyLinkedList list = new SinglyLinkedList(); /** * Three nodes have been allocated dynamically. * We have references to these three blocks as head, * second and third. * * list.head second third * | | | * | | | * +----+------+ +----+------+ +----+------+ * | 1 | null | | 2 | null | | 3 | null | * +----+------+ +----+------+ +----+------+ */ list.head = new Node(1); Node second = new Node(2); Node third = new Node(3); /** * Now next of the first Node refers to the second. So they * both are linked. * * list.head second third * | | | * | | | * +----+------+ +----+------+ +----+------+ * | 1 | o-------->| 2 | null | | 3 | null | * +----+------+ +----+------+ +----+------+ */ list.head.next = second; /** * Now next of the second Node refers to third. So all three nodes are linked. * * list.head second third * | | | * | | | * +----+------+ +----+------+ +----+------+ * | 1 | o-------->| 2 | o-------->| 3 | null | * +----+------+ +----+------+ +----+------+ */ second.next = third; Node current = list.head; while (current != null) { System.out.print(current.data + " "); current = current.next; } }}
輸出
1 2 3
最新評論