數據結構與算法 | 線性表 —— 鏈表

pexels-photo-1322185

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

鏈表

定義

邏輯結構上一個挨一個的數據,在實際存儲時,並無像順序表那樣也相互緊挨着。偏偏相反,數據隨機分佈在內存中的各個位置,這種存儲結構稱爲線性表的鏈式存儲java

因爲分散存儲,爲了可以體現出數據元素之間的邏輯關係,每一個數據元素在存儲的同時,要配備一個指針,用於指向它的直接後繼元素,即每個數據元素都指向下一個數據元素(最後一個指向NULL(空))。這種結構成爲 "單向鏈表"。node

SingleLinkedList

在單向鏈表的基礎上,給各個結點額外配備一個指針變量,用於指向每一個結點的直接前趨元素。這樣的鏈表被稱爲「雙向鏈表」或者「雙鏈表」。git

DoublyLinkedList

當單向鏈表的尾部數據指向頭部數據時,就構成了單向循環鏈表github

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;
        }
    }
}

複製代碼

源代碼ide

雙向鏈表

相比於單向鏈表,雙向鏈表多了一個前驅指針,在查找前驅節點時,時間複雜度下降爲了O(1)。post

經過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

參考資料

相關文章
相關標籤/搜索