Skip to content

1171. Remove Zero Sum Consecutive Nodes from Linked List

https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var removeZeroSumSublists = function(head) {
    const dummy = new ListNode()
    dummy.next = head

    const map = { 0: dummy }
    let sum = 0

    while (head) {
        sum += head.val
        if (map[sum]) {
            let temp = map[sum].next
            let delSum = sum
            while (temp != head) {
                delSum += temp.val
                delete map[delSum]
                temp = temp.next
            }
            map[sum].next = head.next
        } else {
            map[sum] = head
        }
        head = head.next
    }

    return dummy.next
};