資料結構與演算法 | 線性表 —— 連結串列

wangwei_hz發表於2018-12-29

pexels-photo-1322185

原文連結:wangwei.one/posts/java-…

連結串列

定義

邏輯結構上一個挨一個的資料,在實際儲存時,並沒有像順序表那樣也相互緊挨著。恰恰相反,資料隨機分佈在記憶體中的各個位置,這種儲存結構稱為線性表的鏈式儲存

由於分散儲存,為了能夠體現出資料元素之間的邏輯關係,每個資料元素在儲存的同時,要配備一個指標,用於指向它的直接後繼元素,即每一個資料元素都指向下一個資料元素(最後一個指向NULL(空))。這種結構成為 "單向連結串列"。

SingleLinkedList

在單向連結串列的基礎上,給各個結點額外配備一個指標變數,用於指向每個結點的直接前趨元素。這樣的連結串列被稱為“雙向連結串列”或者“雙連結串列”。

DoublyLinkedList

當單向連結串列的尾部資料指向頭部資料時,就構成了單向迴圈連結串列

SinglyCircularLinkedList

當雙向連結串列的頭部和尾部相互指向時,就構成了雙向迴圈連結串列

DoublyCircularLinkedList

單向連結串列

單向連結串列在插入元素、刪除元素時,需要獲取前驅元素,需要從head開始遍歷,時間複雜度為O(n)。

根據index查詢對應元素,也需要從head開始遍歷,時間複雜度為O(n)。

程式碼實現

package one.wangwei.algorithms.datastructures.list.impl;

import one.wangwei.algorithms.datastructures.list.IList;

/**
 * Single Linked List
 *
 * @author https://wangwei.one
 * @date 2018/12/25
 */
public class SingleLinkedList<T> implements IList<T> {

    /**
     * size
     */
    private int size = 0;
    /**
     * head node
     */
    private Node<T> head;
    /**
     * tail node
     */
    private Node<T> tail;

    /**
     * add element
     *
     * @param element
     * @return
     */
    @Override
    public boolean add(T element) {
        return addLast(element);
    }

    /**
     * add element at index
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public boolean add(int index, T element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        if (index == size) {
            return add(element);
        } else {
            return addBefore(index, element);
        }
    }

    /**
     * Add Last element
     *
     * @param element
     * @return
     */
    private boolean addLast(T element) {
        Node<T> last = tail;
        Node<T> newNode = new Node<>(null, element);
        tail = newNode;
        // if linked list is empty
        if (last == null) {
            head = newNode;
        } else {
            last.next = newNode;
        }
        size++;
        return true;
    }

    /**
     * add element before certain element
     *
     * @param index
     * @param element
     * @return
     */
    private boolean addBefore(int index, T element) {
        checkPositionIndex(index);
        // prev node
        Node<T> prev = null;
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            prev = x;
            x = x.next;
        }
        // current node
        Node<T> current = x;
        // new node
        Node<T> newNode = new Node<>(current, element);
        // if current node is head
        if (prev == null) {
            head = newNode;
        } else {
            prev.next = newNode;
        }
        size++;
        return true;
    }

    /**
     * remove element
     *
     * @param element
     * @return
     */
    @Override
    public boolean remove(T element) {
        Node<T> prev = null;
        Node<T> x = head;
        if (element == null) {
            while (x != null && x.element != null) {
                prev = x;
                x = x.next;
            }
        } else {
            while (x != null && !x.element.equals(element)) {
                prev = x;
                x = x.next;
            }
        }

        // if this linked is null OR don't find element
        if (x == null) {
            return false;
        }

        Node<T> next = x.next;

        // if delete node is head
        if (prev == null) {
            head = next;
        } else {
            prev.next = next;
        }
        // if delete node is tail
        if (next == null) {
            tail = prev;
        }

        // for GC
        x.element = null;
        x = null;

        size--;
        return true;
    }

    /**
     * remove element by index
     *
     * @param index
     * @return
     */
    @Override
    public T remove(int index) {
        checkPositionIndex(index);
        Node<T> prev = null;
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            prev = x;
            x = x.next;
        }

        // if linked is empty
        if (x == null) {
            return null;
        }

        Node<T> next = x.next;

        // if delete node is head
        if (prev == null) {
            head = next;
        } else {
            prev.next = next;
        }

        // if delete node is tail
        if (next == null) {
            tail = prev;
        }
        size--;
        return x.element;
    }

    /**
     * set element by index
     *
     * @param index
     * @param element
     * @return old element
     */
    @Override
    public T set(int index, T element) {
        checkPositionIndex(index);
        Node<T> node = node(index);
        T oldElement = node.element;
        node.element = element;
        return oldElement;
    }
    
    /**
     * get element by index
     *
     * @param index
     * @return
     */
    @Override
    public T get(int index) {
        Node<T> node = node(index);
        return node == null ? null : node.element;
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    private Node<T> node(int index) {
        checkPositionIndex(index);
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            x = x.next;
        }
        return x;
    }

    /**
     * check index
     *
     * @param index
     */
    private void checkPositionIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }

    /**
     * clear list
     */
    @Override
    public void clear() {
        for (Node<T> x = head; x != null; ) {
            Node<T> next = x.next;
            x.element = null;
            x.next = null;
            x = next;
        }
        head = tail = null;
        size = 0;
    }

    /**
     * contain certain element
     *
     * @param element
     */
    @Override
    public boolean contains(T element) {
        if (element == null) {
            for (Node<T> x = head; x != null; x = x.next) {
                if (x.element == null) {
                    return true;
                }
            }
        } else {
            for (Node<T> x = head; x != null; x = x.next) {
                if (x.element.equals(element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * get list size
     *
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * Linked List Node
     *
     * @param <T>
     */
    private class Node<T> {
        private Node<T> next;
        private T element;

        public Node(Node<T> next, T element) {
            this.next = next;
            this.element = element;
        }
    }
}

複製程式碼

原始碼

雙向連結串列

相比於單向連結串列,雙向連結串列多了一個前驅指標,在查詢前驅節點時,時間複雜度降低為了O(1)。

通過index查詢,刪除某個node節點,時間複雜度都降為了O(1)。程式碼如下:

程式碼實現

package one.wangwei.algorithms.datastructures.list.impl;

import one.wangwei.algorithms.datastructures.list.IList;

/**
 * Doubly Linked List
 *
 * @param <T>
 * @author https://wangwei.one
 * @date 2018/04/28
 */
public class DoublyLinkedList<T> implements IList<T> {

    /**
     * size
     */
    private int size = 0;
    /**
     * head element
     */
    private Node<T> head = null;
    /**
     * tail element
     */
    private Node<T> tail = null;

    /**
     * add element
     *
     * @param element
     * @return
     */
    @Override
    public boolean add(T element) {
        return addLast(element);
    }

    /**
     * add element at index
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public boolean add(int index, T element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        if (index == size) {
            return add(element);
        } else {
            return addBefore(element, node(index));
        }
    }

    /**
     * Add Last element
     *
     * @param element
     * @return
     */
    private boolean addLast(T element) {
        final Node<T> last = tail;
        Node<T> newNode = new Node<>(last, element, null);
        tail = newNode;
        if (last == null) {
            head = newNode;
        } else {
            last.next = newNode;
        }
        size++;
        return true;
    }

    /**
     * add element before certain element
     *
     * @param element
     * @param target
     * @return
     */
    private boolean addBefore(T element, Node<T> target) {
        Node<T> prev = target.prev;
        Node<T> newNode = new Node<>(prev, element, target);
        target.prev = newNode;
        if (prev == null) {
            head = newNode;
        } else {
            prev.next = newNode;
        }
        size++;
        return true;
    }

    /**
     * remove node by element
     *
     * @param element
     * @return
     */
    @Override
    public boolean remove(T element) {
        if (element == null) {
            for (Node<T> x = head; x != null; x = x.next) {
                if (x.element == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<T> x = head; x != null; x = x.next) {
                if (element.equals(x.element)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * remove node by index
     *
     * @param index
     * @return
     */
    @Override
    public T remove(int index) {
        return unlink(node(index));
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    private Node<T> node(int index) {
        checkPositionIndex(index);
        if (index < (size >> 1)) {
            Node<T> x = head;
            for (int i = 0; i < index; i++) {
                x = x.next;
            }
            return x;
        } else {
            Node<T> x = tail;
            for (int i = size - 1; i > index; i--) {
                x = x.prev;
            }
            return x;
        }
    }

    /**
     * unlink node
     *
     * @param node
     */
    private T unlink(Node<T> node) {
        final T element = node.element;
        final Node<T> prev = node.prev;
        final Node<T> next = node.next;

        // if unlink is head
        if (prev == null) {
            head = next;
        } else {
            prev.next = next;
            // clear prev
            node.prev = null;
        }

        // if unlink is tail
        if (next == null) {
            tail = prev;
        } else {
            next.prev = prev;
            node.next = null;
        }

        node.element = null;
        size--;
        return element;
    }

    private void checkPositionIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }

    /**
     * set element by index
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public T set(int index, T element) {
        checkPositionIndex(index);
        Node<T> oldNode = node(index);
        T oldElement = oldNode.element;
        oldNode.element = element;
        return oldElement;
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    @Override
    public T get(int index) {
        Node<T> node = node(index);
        return node == null ? null : node.element;
    }

    /**
     * clear list
     */
    @Override
    public void clear() {
        for (Node<T> x = head; x != null; ) {
            Node<T> next = x.next;
            x.element = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        head = tail = null;
        size = 0;
    }

    /**
     * contain certain element
     *
     * @param element
     */
    @Override
    public boolean contains(T element) {
        if (element == null) {
            for (Node<T> x = head; x != null; x = x.next) {
                if (x.element == null) {
                    return true;
                }
            }
        } else {
            for (Node<T> x = head; x != null; x = x.next) {
                if (element.equals(x.element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * get list size
     *
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * node
     *
     * @param <T>
     */
    private class Node<T> {

        private T element;
        private Node<T> prev;
        private Node<T> next;

        public Node(Node<T> prev, T element, Node<T> next) {
            this.element = element;
            this.prev = prev;
            this.next = next;
        }
    }

}

複製程式碼

原始碼

單向迴圈連結串列

與單向連結串列一樣,在尋找前驅節點時,需要遍歷整個連結串列,時間複雜度為O(n).

在第一次新增元素時,特別注意,head與tail為同一節點,並且需要自指向。

package one.wangwei.algorithms.datastructures.list.impl;

import one.wangwei.algorithms.datastructures.list.IList;

/**
 * Singly Circular Linked List
 *
 * @param <T>
 * @author https://wangwei.one
 * @date 2018/05/03
 */
public class SinglyCircularLinkedList<T> implements IList<T> {

    /**
     * size
     */
    private int size = 0;
    /**
     * head node
     */
    private Node<T> head = null;
    /**
     * tail node
     */
    private Node<T> tail = null;

    /**
     * add element
     *
     * @param element
     * @return
     */
    @Override
    public boolean add(T element) {
        return addLast(element);
    }

    /**
     * add element at index
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public boolean add(int index, T element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        if (index == size) {
            return add(element);
        } else {
            return addBefore(index, element);
        }
    }

    /**
     * Add Last element
     *
     * @param element
     * @return
     */
    private boolean addLast(T element) {
        final Node<T> last = tail;
        Node<T> newElement = new Node<>(element, head);
        tail = newElement;
        if (last == null) {
            head = newElement;
            // we need linked itself when add an element first
            tail.next = head;
        } else {
            last.next = newElement;
        }
        size++;
        return true;
    }

    /**
     * add element before certain element
     *
     * @param element
     * @param element
     * @return
     */
    private boolean addBefore(int index, T element) {
        checkPositionIndex(index);
        // prev node, start with tail
        Node<T> prev = tail;
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            prev = x;
            x = x.next;
        }
        // current node
        Node<T> current = x;
        // new node
        Node<T> newNode = new Node<>(element, current);
        if (index == 0) {
            head = newNode;
        }
        prev.next = newNode;
        size++;
        return true;
    }

    /**
     * remove node by element
     *
     * @param element
     * @return
     */
    @Override
    public boolean remove(T element) {
        // start with tail
        Node<T> prev = tail;
        // start with head
        Node<T> x = head;
        // start with index -1
        int prevIndex = -1;

        for (int i = 0; i < size; i++) {
            if (element == null && x.element == null) {
                break;
            }
            if (element != null && element.equals(x.element)) {
                break;
            }
            prev = x;
            x = x.next;
            prevIndex = i;
        }

        // if this linked list is empty
        if (x == null) {
            return false;
        }

        // if don't match element
        if (prevIndex == size - 1) {
            return false;
        }

        Node<T> next = x.next;

        // if delete node is head
        if (prevIndex == -1) {
            head = next;
        }

        // if delete node is tail
        if (prevIndex == size - 2) {
            tail = prev;
        }

        prev.next = next;

        size--;

        if (size == 0) {
            head = tail = null;
        }

        // for GC
        x = null;

        return true;
    }

    /**
     * remove element by index
     *
     * @param index
     * @return
     */
    @Override
    public T remove(int index) {
        checkPositionIndex(index);
        Node<T> prev = tail;
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            prev = x;
            x = x.next;
        }

        // if linked is empty
        if (x == null) {
            return null;
        }

        Node<T> next = x.next;

        // if delete node is head
        if (index == 0) {
            head = next;
        }

        // if delete node is tail
        if (index == size - 1) {
            tail = prev;
        }

        prev.next = next;

        size--;

        if (size == 0) {
            head = tail = null;
        }

        return x.element;
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    private Node<T> node(int index) {
        checkPositionIndex(index);
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            x = x.next;
        }
        return x;
    }

    private void checkPositionIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }

    /**
     * set element by index
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public T set(int index, T element) {
        checkPositionIndex(index);
        Node<T> oldNode = node(index);
        T oldElement = oldNode.element;
        oldNode.element = element;
        return oldElement;
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    @Override
    public T get(int index) {
        return node(index).element;
    }

    /**
     * clear list element
     */
    @Override
    public void clear() {
        for (Node<T> x = head; x != null; ) {
            Node<T> next = x.next;
            x.element = null;
            x.next = null;
            x = next;
        }
        head = tail = null;
        size = 0;
    }

    /**
     * contain certain element
     *
     * @param element
     */
    @Override
    public boolean contains(T element) {
        if (head == null) {
            return false;
        }
        Node<T> x = head;
        for (int i = 0; i < size; i++) {
            if (element == null && x.element == null) {
                return true;
            }
            if (element != null && element.equals(x.element)) {
                return true;
            }
            x = x.next;
        }
        return false;
    }

    /**
     * get list size
     *
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * Node
     *
     * @param <T>
     */
    private class Node<T> {

        private T element;
        private Node<T> next;

        public Node(T element, Node<T> next) {
            this.element = element;
            this.next = next;
        }
    }
}

複製程式碼

原始碼

雙向迴圈連結串列

雙向迴圈連結串列相比單向迴圈連結串列,降低了查詢前驅節點的複雜度,時間複雜度為O(1).

同樣第一次新增元素時,head與tail為同一元素,需要自指向。

package one.wangwei.algorithms.datastructures.list.impl;

import one.wangwei.algorithms.datastructures.list.IList;

/**
 * Doubly circular linked list
 *
 * @author https://wangwei.one
 * @date 2018/12/21
 */
public class DoublyCircularLinkedList<T> implements IList<T> {

    /**
     * size
     */
    private int size;
    /**
     * head node
     */
    private Node<T> head;
    /**
     * tail node
     */
    private Node<T> tail;

    /**
     * add element
     *
     * @param element
     * @return
     */
    @Override
    public boolean add(T element) {
        return addLast(element);
    }

    /**
     * add element at index
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public boolean add(int index, T element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        if (index == size) {
            return add(element);
        } else {
            return addBefore(index, element);
        }
    }

    /**
     * Add last element
     *
     * @param element
     * @return
     */
    private boolean addLast(T element) {
        Node<T> last = tail;
        Node<T> newNode = new Node<>(element, last, head);
        tail = newNode;
        // add element at first
        if (last == null) {
            head = newNode;
            tail.next = head;
        } else {
            last.next = newNode;
        }
        head.prev = tail;
        size++;
        return true;
    }

    /**
     * add element before certain element
     *
     * @param index
     * @param element
     * @return
     */
    private boolean addBefore(int index, T element) {
        Node<T> target = node(index);
        Node<T> prev = target.prev;
        Node<T> newNode = new Node<>(element, prev, target);

        prev.next = newNode;
        target.prev = newNode;

        if (index == 0) {
            head = newNode;
        }

        size++;
        return true;
    }

    /**
     * remove element
     *
     * @param element
     * @return
     */
    @Override
    public boolean remove(T element) {
        // start with head
        Node<T> x = head;
        // start with index -1
        int prevIndex = -1;

        for (int i = 0; i < size; i++) {
            if (element == null && x.element == null) {
                break;
            }
            if (element != null && element.equals(x.element)) {
                break;
            }
            x = x.next;
            prevIndex = i;
        }

        // if this linked list is empty
        if (x == null) {
            return false;
        }

        // if don't match element
        if (prevIndex == size - 1) {
            return false;
        }

        Node<T> prev = x.prev;
        Node<T> next = x.next;

        // if delete node is head
        if (prevIndex == -1) {
            head = next;
        }

        // if delete node is tail
        if (prevIndex == size - 2) {
            tail = prev;
        }

        prev.next = next;
        next.prev = prev;

        size--;

        if (size == 0) {
            head = tail = null;
        }

        // for GC
        x = null;

        return true;
    }

    /**
     * remove element by index
     *
     * @param index
     * @return
     */
    @Override
    public T remove(int index) {
        checkPositionIndex(index);
        Node<T> x = head;
        for (int i = 0; i < index; i++) {
            x = x.next;
        }

        // if linked is empty
        if (x == null) {
            return null;
        }

        Node<T> prev = x.prev;
        Node<T> next = x.next;

        // if delete node is head
        if (index == 0) {
            head = next;
        }

        // if delete node is tail
        if (index == size - 1) {
            tail = prev;
        }

        prev.next = next;
        next.prev = prev;

        size--;

        if (size == 0) {
            head = tail = null;
        }

        return x.element;
    }

    private void checkPositionIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }

    /**
     * set element by index
     *
     * @param index
     * @param element
     * @return old element
     */
    @Override
    public T set(int index, T element) {
        Node<T> oldNode = node(index);
        T oldElement = oldNode.element;
        oldNode.element = element;
        return oldElement;
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    @Override
    public T get(int index) {
        return node(index).element;
    }

    /**
     * get element by index
     *
     * @param index
     * @return
     */
    private Node<T> node(int index) {
        checkPositionIndex(index);
        if (index < (size >> 1)) {
            Node<T> x = head;
            for (int i = 0; i < index; i++) {
                x = x.next;
            }
            return x;
        } else {
            Node<T> x = tail;
            for (int i = size - 1; i > index; i--) {
                x = x.prev;
            }
            return x;
        }
    }

    /**
     * clear list
     */
    @Override
    public void clear() {
        for (Node<T> x = head; x != null; ) {
            Node<T> next = x.next;
            x.element = null;
            x.next = null;
            x = next;
        }
        head = tail = null;
        size = 0;
    }

    /**
     * contain certain element
     *
     * @param element
     * @return
     */
    @Override
    public boolean contains(T element) {
        if (head == null) {
            return false;
        }
        Node<T> x = head;
        for (int i = 0; i < size; i++) {
            if (element == null && x.element == null) {
                return true;
            }
            if (element != null && element.equals(x.element)) {
                return true;
            }
            x = x.next;
        }
        return false;
    }

    /**
     * get list size
     *
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * Node
     *
     * @param <T>
     */
    private class Node<T> {
        private T element;
        private Node<T> prev;
        private Node<T> next;

        public Node(T element, Node<T> prev, Node<T> next) {
            this.element = element;
            this.prev = prev;
            this.next = next;
        }
    }

}

複製程式碼

原始碼

ArrayList vs LinkedList

ArrayList LinkedList
插入&
刪除
O(n) O(1)
隨機訪問 O(1) O(n)
優點 連續的記憶體空間,可以藉助CPU的預取機制 記憶體不連續,天然支援動態擴容
缺點 無法儲存大資料,陣列擴容耗效能 頻繁地插入刪除操作,會導致記憶體碎片的增加,導致頻繁的GC

參考資料

相關文章