#2181
Medium Algorithms Merge nodes in between zeros
Linked List Simulation
89.7% acceptance
Feb 23, 2026
2494
53
You are given the head of a linked list with series of integers separated by 0's.
The beginning and end of the list have Node.val == 0.
For every two consecutive 0's, merge all nodes between them into a single node
whose value is the sum of all merged nodes. Return the head of the modified list.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn merge_nodes(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut values = Vec::new();
let mut cur = head;
let mut sum = 0i32;
// Skip the leading 0
cur = cur?.next;
while let Some(node) = cur {
if node.val == 0 {
values.push(sum);
sum = 0;
} else {
sum += node.val;
}
cur = node.next;
}
// Build result list
let mut dummy = Box::new(ListNode::new(0));
let mut tail = &mut dummy;
for v in values {
tail.next = Some(Box::new(ListNode::new(v)));
tail = tail.next.as_mut().unwrap();
}
dummy.next
}
}