欢迎!点击下方按钮体验链表操作

JavaScript 实现

// 链表节点定义
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// 链表类
class LinkedList {
    constructor() {
        this.head = null;
        this.size = 0;
    }

    // 头部插入 - O(1)
    addHead(data) {
        const node = new Node(data);
        node.next = this.head;
        this.head = node;
        this.size++;
    }

    // 尾部插入 - O(n)
    addTail(data) {
        const node = new Node(data);
        if (!this.head) {
            this.head = node;
        } else {
            let cur = this.head;
            while (cur.next) cur = cur.next;
            cur.next = node;
        }
        this.size++;
    }

    // 搜索 - O(n)
    search(data) {
        let cur = this.head;
        let index = 0;
        while (cur) {
            if (cur.data === data) return index;
            cur = cur.next;
            index++;
        }
        return -1;
    }

    // 删除 - O(n)
    remove(data) {
        if (!this.head) return false;
        if (this.head.data === data) {
            this.head = this.head.next;
            this.size--;
            return true;
        }
        let cur = this.head;
        while (cur.next) {
            if (cur.next.data === data) {
                cur.next = cur.next.next;
                this.size--;
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    // 反转 - O(n)
    reverse() {
        let prev = null;
        let cur = this.head;
        while (cur) {
            const next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        this.head = prev;
    }
}

时间复杂度分析(与数组对比)

操作链表数组说明
访问O(n)O(1)链表需要遍历,数组直接寻址
搜索O(n)O(n)都需要遍历
头部插入O(1)O(n)链表只需改指针
头部删除O(1)O(n)链表只需改指针
中间插入O(n)O(n)都要先定位,链表插入本身O(1)
末尾插入O(n)O(1)链表需遍历到尾,数组直接追加
空间额外指针连续紧凑链表每个节点多存一个指针