#2181

Merge Nodes in Between Zeros

pupil · 360 · lc medium +23 · verified · 89.7% accepted · 2,495 likes · top 99%

Description

You are given the head of a linked list that contains a series of integers with 0s as separators. The first and last nodes both have val == 0.

For each pair of consecutive 0s, replace all intermediate nodes with a single node whose value is their sum. The resulting list should contain no 0s.

Return the head of the modified linked list.

Example 1:

Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.

Example 2:

Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.

Code

1
2
3
4
5
6
7
8