You are given the <code>head</code> of a linked list, which contains a series of integers <strong>separated</strong> by <code>0</code>‘s. The <strong>beginning</strong> and <strong>end</strong> of the linked list will have <code>Node.val == 0</code>.For <strong>every</strong> two consecutive <code>0</code>‘s, <strong>merge</strong> all the nodes lying in between them into a single node whose value is the <strong>sum</strong> of all the merged nodes. The modified list should not contain any <code>0</code>‘s.Return <em>the head of the modified linked list</em>.
Input: head = [0,3,1,0,4,5,2,0]Output: [4,11]Explanation: The modified list contains the sum of the nodes marked in green: 3 + 1 = 4, and the sum of the nodes marked in red: 4 + 5 + 2 = 11.
Input: head = [0,1,0,3,0,2,2,0]Output: [1,3,4]Explanation: The modified list contains the sum of the nodes marked in green: 1 = 1, the sum of the nodes marked in red: 3 = 3, and the sum of the nodes marked in yellow: 2 + 2 = 4.
from leetcode_py import ListNodeclass Solution: # Time: O(n) where n is the number of nodes in the input list # Space: O(1), nodes are merged in place def merge_nodes(self, head: ListNode[int] | None) -> ListNode[int] | None: if head is None: return None tail = head node = head.next total = 0 first = True while node is not None: if node.val == 0: if first: head.val = total first = False else: nxt = tail.next assert nxt is not None nxt.val = total tail = nxt total = 0 else: total += node.val node = node.next tail.next = None return head