Skip to main content
LeetCode 2181, Medium. Topics: Linked List, Simulation. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

Problem

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

Examples

Example 1
Example 2

Constraints

  • The number of nodes in the list is in the range [3, 2 * 10^5].
  • 0 <= Node.val <= 1000
  • There are no two consecutive nodes with Node.val == 0.
  • The beginning and end of the linked list have Node.val == 0.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026