Merge Nodes in Between Zeros

Medium

Topics
Linked ListSimulation

You are given the head of a linked list that begins and ends with 0; between every pair of consecutive 0s there is at least one node. Merge each block of nodes between two zeros into a single node whose value is their sum, then return the resulting list (which no longer contains any 0).

Example 1

Input:  head = [0,3,1,0,4,5,2,0]
Output: [4,11]

Example 2

Input:  head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]

Constraints

  • 3 <= number of nodes <= 2*10^5
  • 0 <= Node.val <= 1000
  • The list starts and ends with 0.
Run ⌘' · Submit ⌘⏎