<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
class Solution:
    def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
        l = [] # val-s from linked list
        while head:
            if head.val != 0:
                l.append(head.val)
            head = head.next
        if not l:
            return None
        # gen pref-sums
        p = [l[0]]
        for i in range(1, len(l)):
            p.append(p[i-1] + l[i])
        print(l)
        print(p)
        nulls = []
        i = 0
        j = 0
        while i < len(l)-1:
            j = i + 1
            while j < len(l):
                left = 0
                if i > 0:
                    left = p[i-1]
                right = p[j]

                if right - left == 0:
                    nulls.append([i, j])
                    i = j
                    break         
                j += 1
            i += 1

        print(nulls)
        l_res = []
        for i in range(len(l)-1, -1, -1):
            if nulls and (nulls[-1][0] > i):
                nulls.pop()
            if nulls and (nulls[-1][0] <= i <= nulls[-1][1]):
                continue
            l_res.append(l[i])
        l_res = l_res[::-1]

        if not l_res:
            return None
        ans = ListNode(val=l_res[-1])
        for i in range(len(l_res)-2, -1, -1):
            temp = ListNode(val=l_res[i])
            temp.next = ans
            ans = temp

        return ans


        

        

111