[Leetcode]1171.RemoveZeroSumConsecutiveNodesFromLinkedList

72 阅读1分钟

Description:
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.

After doing so, return the head of the final linked list.  You may return any such answer.

Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.

    The following answer's complexity is O(n) in both time and space, and is very easy to understand:leetcode-solution-1171
    if P1 + P2 = P1 + P2 + P3 + P4 + P5, it means the sum of P3 + P4 + P5 is 0. As the sum is consecutive sequences of nodes. The specular attention need to be paid is that the sum of linked list is 0, and a 0 node is added before the head which can track linked list and trackle this situation.

fun removeZeroSumSublists(head: ListNode?): ListNode? {
    // 1. the head need to remove; 2.the sum of linked list is 0;
    val preHead = ListNode(0)
    preHead.next = head
    
    // including the sum of whole linked list is 0.
    var cur: ListNode? = preHead
    val map = mutableMapOf<Int, ListNode>()
    var sum = 0
    while (cur != null) {
        sum += cur.`val`
        map[sum] = cur
        cur = cur.next
    }

    sum = 0
    cur = preHead
    while (cur != null) {
        sum += cur.`val`
        cur.next = map[sum]?.next
        cur = cur.next
    }

    return preHead.next
}