代码:

class ListNode {
    /**
     * @constructor
     * @param {number} val 
     * @param {ListNode} next 
     */
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }

    /**
     * 在n0节点后插入新节点
     * @param {ListNode} n0 
     * @param {ListNode} P 
     */
    insert(n0, P) {
        const n1 = n0.next;
        P.next = n1;
        n0.next = P;
    }

    /**
     * 删除n0后的节点
     * @param {ListNode} n0 
     */
    remove(n0) {
        if (!n0.next) {
            return;
        }
        const P = n0.next;
        const n1 = P.next;
        n0.next = n1;
    }

    /**
     * 访问链表中第index个元素
     * @param {ListNode} head 
     * @param {number} index
     * @return {ListNode}
     */
    access(head, index) {
        for (let i = 0; i < index; i++) {
            if (!head) {
                return null;
            }
            head = head.next;
        }

        return head;
    }

    /**
     * 查找值为target的首个节点的索引
     * @param {ListNode} head 
     * @param {ListNode} target
     */
    find(head, target) {
        let index = 0;
        while (head !== null) {
            if (head.val === target) {
                return index;
            }
            head = head.next;
            index += 1;
        }

        return -1;
    }
}

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。