<p>Given the <code>head</code> of a linked list, we repeatedly delete consecutive sequences of nodes that sum to <code>0</code> until there are no such sequences.</p>

<p>After doing so, return the head of the final linked list.&nbsp; You may return any such answer.</p>

<p>&nbsp;</p>
<p>(Note that in the examples below, all sequences are serializations of <code>ListNode</code> objects.)</p>

<p><strong class="example">Example 1:</strong></p>

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

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> head = [1,2,3,-3,4]
<strong>Output:</strong> [1,2,4]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> head = [1,2,3,-3,-2]
<strong>Output:</strong> [1]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The given linked list will contain between <code>1</code> and <code>1000</code> nodes.</li>
	<li>Each node in the linked list has <code>-1000 &lt;= node.val &lt;= 1000</code>.</li>
</ul>

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# 0 = sum(0..j) - sum(0..i-1)
#.   prefix_sum = sum(0..i-1)
#  1  2  -1  1   
# 
class Solution:
    def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
        sentinel_head = ListNode(None, head)
        curr_node = head
        prefix_sum_before = {0:sentinel_head}
        prefix_sum = 0
        prev = sentinel_head
        prefix_sum_stk = [0]

        while curr_node:
            if curr_node.val == 0:
                prev.next = curr_node.next
                curr_node = curr_node.next
            else:
                prefix_sum += curr_node.val
                old_prev = prev
                print(curr_node.val, prefix_sum, prefix_sum_before.keys())
                if prefix_sum in prefix_sum_before:
                    before_node = prefix_sum_before[prefix_sum]
                    after_node = curr_node.next
                    before_node.next = after_node
                    prev, curr_node = before_node, after_node

                    while prefix_sum_stk and prefix_sum_stk[-1] != prefix_sum:
                        prefix_sum_to_del = prefix_sum_stk.pop()
                        del prefix_sum_before[prefix_sum_to_del]
                else:
                    prefix_sum_before[prefix_sum] = curr_node
                    prefix_sum_stk.append(prefix_sum)
                    prev, curr_node = curr_node, curr_node.next
                    
        return sentinel_head.next




        
130