首頁>技術>

單鏈表

為什麼選擇單鏈表

優點

單鏈表用於儲存相同型別的元素,其大小沒有限制向連結串列中插入元素速度快

缺點

不能夠隨機訪問,必須從第一個元素開始每個指標需要額外的記憶體對於快取很不友好實現

連結串列的第一個元素稱為頭(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 

6
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 深入探索Android效能最佳化