1171. Remove Zero Sum Consecutive Nodes from Linked List

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1171

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(next=head)
        last = {}
        s = 0
        cur = dummy
        while cur:
            s += cur.val
            last[s] = cur
            cur = cur.next

        s = 0 
        cur = dummy
        while cur:
            s += cur.val
            cur.next = last[s].next
            cur = cur.next
        return dummy.next