<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>

class Solution {
public:
    ListNode* removeZeroSumSublists(ListNode* head) {
        ListNode* newlist = new ListNode(0);  // Create a dummy node.
        ListNode* newhead = newlist;          // Pointer to keep track of new head.
        ListNode* temp1 = head;               // Pointer to iterate through the original list.

        while (temp1 != NULL) {               
            int sum = 0;                      
            ListNode* temp2 = temp1;          

            while (temp2 != NULL) {           
                sum = sum + temp2->val;       
                if (sum == 0) {               
                    temp1 = temp2->next;      // Skip zero-sum sublist.
                    break;                    
                }
                temp2 = temp2->next;          
            }

            if (sum != 0) {                   
                ListNode* newnode = new ListNode(temp1->val); // Create new node.
                newlist->next = newnode;      
                newlist = newnode;            
                temp1 = temp1->next;          
            }
        }

        ListNode* result = newhead->next;  // Get the actual result list.

        // Cleanup dummy node (newhead) and any other unused nodes.
        delete newhead;  // Delete the dummy node to avoid memory leak.

        return result;
    }
};

14700