JS 鏈表 - 筆記

代碼:

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章