使用js实现一个链表

82 阅读1分钟

使用js实现一个链表

class linkNode {
    constructor(val, next) {
        this.val = val;
        this.next = next;
    }
}

class linkedList {
    constructor() {
        //初始化一个空链表
        this._size = 0;
        this._head = null; //头结点
        this._tail = null; //尾节点
    }
    //在头节点前加入节点
    addAtHead(val) {
        const node = new linkNode(val, this._head);
        this._head = node;
        this._size++;
        !this._tail && (this._tail = node);
    }
    //在末尾加入节点
    addAtTail(val) {
        const node = new linkNode(val, null);
        if (this._tail) {
            this._tail.next = node;
        } else {
            this._head = node;
        }
        this._size++;
        this._tail = node;
    }
    //在链表中的第index 个节点之前添加值为 val 的节点。
    addAtIndex(index, val) {
        if (index < 0 || index >= this._size) {
            throw "addAtIndex()索引不存在";
        }

        // 需要先查出第index - 1的节点
        let lest = null;
        let count = 0;
        while (count <= index - 1) {
            lest = lest ? lest.next : this._head;
            count++;
        }
        // 查出index节点
        let current = lest ? lest.next : this._head;
        const node = new linkNode(val, current);
        !lest ? (this._head = node) : (lest.next = node);
        !current && (this._tail = node);
        this._size++;
    }
    //获取第index 个节点。
    getByIndex(index) {
        if (index < 0 || index >= this._size) {
            throw "getByIndex()索引不存在";
        }
        let currentNode = this._head;
        let count = 0;
        while (count <= index - 1) {
            currentNode = currentNode.next;
            count++;
        }
        return currentNode;
    }
    // deleteAtIndex
    deleteAtIndex(index) {
        if (index < 0 || index >= this._size) {
            throw "getByIndex()索引不存在";
        }
        // 需要先查出第index - 1的节点
        let lest = null;
        let count = 0;
        while (count <= index - 1) {
            lest = lest ? lest.next : this._head;
            count++;
        }
        // 查出当前节点
        let current = lest ? lest.next : this._head;
        // 查出下一个节点
        let next = current ? current.next : this._head;
        // 设置前一个节点
        lest ? (lest.next = next) : (this._head = next);
        // 设置后一个节点
        !next && (this._tail = next);
        this._size--;
    }
}
const list = new linkedList();
list.addAtHead(2);
list.addAtHead(5);
list.addAtHead(100);
list.addAtHead(5200);
list.addAtIndex(3, 111);
console.log(list);