Merge Nodes in Between Zeros

medium linked list simulation

Problem

The head of a linked list starts with 0 and ends with 0, with no consecutive zeros in between. Merge the nodes between each pair of consecutive zeros into a single node whose value is the sum of those nodes. The zeros themselves are removed.

Inputhead = [0, 3, 1, 0, 4, 5, 2, 0]
Output[4, 11]
Sum 3+1=4 between the first two zeros; sum 4+5+2=11 between the next two.

def merge_nodes(head):
    dummy = ListNode(0)
    tail = dummy
    cur = head.next
    s = 0
    while cur:
        if cur.val == 0:
            tail.next = ListNode(s)
            tail = tail.next
            s = 0
        else:
            s += cur.val
        cur = cur.next
    return dummy.next
function mergeNodes(head) {
  const dummy = { val: 0, next: null };
  let tail = dummy;
  let cur = head.next;
  let sum = 0;
  while (cur) {
    if (cur.val === 0) {
      tail.next = { val: sum, next: null };
      tail = tail.next;
      sum = 0;
    } else {
      sum += cur.val;
    }
    cur = cur.next;
  }
  return dummy.next;
}
class Solution {
    public ListNode mergeNodes(ListNode head) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        ListNode cur = head.next;
        int sum = 0;
        while (cur != null) {
            if (cur.val == 0) {
                tail.next = new ListNode(sum);
                tail = tail.next;
                sum = 0;
            } else {
                sum += cur.val;
            }
            cur = cur.next;
        }
        return dummy.next;
    }
}
ListNode* mergeNodes(ListNode* head) {
    ListNode dummy(0);
    ListNode* tail = &dummy;
    ListNode* cur = head->next;
    int sum = 0;
    while (cur) {
        if (cur->val == 0) {
            tail->next = new ListNode(sum);
            tail = tail->next;
            sum = 0;
        } else {
            sum += cur->val;
        }
        cur = cur->next;
    }
    return dummy.next;
}
Time: O(n) Space: O(1) extra (excluding output)