2181. Merge Nodes in Between Zeros¶
Intuition¶
The problem requires merging nodes between zeros in a linked list and returning the modified list without zeros. The solution takes advantage of two pointers: slow to track the current node for merging and fast to traverse the list. By summing values between zeros and connecting nodes appropriately, we can achieve the desired result efficiently.
Approach: Two Pointers¶
Using two pointers, slow and fast, we can traverse the list while merging the values between zeros and adjusting the pointers to form the new linked list.
Explanation:¶
- Initialization:
slowis initialized to the head of the list.fastis initialized to the next node afterhead.- Traverse the List:
- Iterate through the list using the
fastpointer untilfast->nextisnullptr. - Sum Values and Adjust Pointers:
- Summing Values:
- If
fast->valis not 0, addfast->valtoslow->val.
- If
- Adjusting Pointers:
- If
fast->valis 0, it means we've reached the end of a segment to merge. Updateslow->nextto point tofastand moveslowtofast.
- If
- Move the
fastpointer to the next node. - Finalize the List:
- Set
slow->nexttonullptrto ensure the new list terminates correctly. - Return the modified list starting from the head.
Complexity¶
- Time complexity: O(n)
- Space complexity: O(1)