You are given the head
of a linked list, which contains a series of integers separated by 0
's. The beginning and end of the linked list will have Node.val == 0
.
For every two consecutive 0
's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0
's.
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.
Constraints:
[3, 2 * 105]
.0 <= Node.val <= 1000
Node.val == 0
.Node.val == 0
.This problem involves manipulating a linked list where nodes with value 0 act as separators between groups of nodes. The goal is to merge the nodes between each pair of 0s into a single node representing the sum of their values.
The most efficient approach is an iterative traversal of the linked list. We maintain a running sum and create a new linked list to store the results.
Initialization: Create a dummy node dummy
to simplify handling the head of the new list. We'll also have a tail
pointer to track the end of the new list and a sum
variable to accumulate values between zeros.
Iteration: Iterate through the input linked list starting from the node after the initial 0.
Summation: If the current node's value is not 0, add it to the sum
.
Zero Encountered: If a node with value 0 is encountered:
sum
.sum
to 0.tail
pointer to the newly created node.Final Node: After the loop, there might be a remaining sum
. Handle this by creating a final node if necessary.
Return: Return the next
node of the dummy
node, which is the head of the modified linked list.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0) # Dummy node
tail = dummy
current_sum = 0
curr = head.next # Start from the node after the initial 0
while curr:
if curr.val != 0:
current_sum += curr.val
else:
new_node = ListNode(current_sum)
tail.next = new_node
tail = new_node
current_sum = 0
curr = curr.next
return dummy.next # Return the head of the new list
The code in other languages (Java, C++, Go, TypeScript, Rust, C) follows a very similar structure, adapting the syntax and data structures specific to each language. The core logic of iterative traversal, summation, and new node creation remains consistent across all implementations.