🚀 Merge Nodes Between Zeros in Linked List! 🔗 Beats 98%✨ Easiest
\n\n# Intuition\nWhen given a linked list where nodes contain values between zeros, the task is to merge these values into a single node. By traversing the link
![image.png](https://assets.leetcode.com/users/images/cf8ec5cb-4896-4c15-ab45-34d09f2e8973_1720056787.2791822.png)\n\n# Intuition\nWhen given a linked list where nodes contain values between zeros, the task is to merge these values into a single node. By traversing the linked list and summing values until a zero is encountered, we can effectively merge nodes and simplify the list.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialization: Use two pointers, \'l\' (left) starting at the head and \'r\' (right) starting at the node next to the head.\n2. Traversal and Summation:\n\u2022 Traverse the list with \'r\' to accumulate values between zeros.\n\u2022 When encountering a zero, move the \'l\' pointer to the next node and update its value to the accumulated sum.\n\u2022 Reset the sum after updating the value and continue traversing.\n3. Terminate List: After processing all nodes, ensure the next pointer of the last merged node is set to \'none\'.\n4. Retum Result: Retum the next node of the head, which now points to the start of the modified list.\n<!-- Describe your approach to solving the problem. -->\n# Detailed Steps\n1. Traverse List: Iterate through the linked list using the pointer to accumulate values.\n2. Sum and Update: Sum the values between zeros, updating the node pointed by whenever a\nzero is encountered.\n3. Reset and Continue: Reset the sum and continue the traversal, effectively merging the nodes.\n4. End List: Ensure the last node\'s next pointer is set to to terminate the list correctly.\n5. \n# Complexity\n- Time complexity: O(n), where n is the number of nodes in the linked list. Each node is visited exactly once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), as we only use a fixed amount of extra space for pointers and sum variables.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, val=0, next=None):\n#         self.val = val\n#         self.next = next\nclass Solution:\n    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        l = head\n        r = head.next\n\n        sum = 0\n        while r:\n            if r.val == 0:\n                l = l.next\n                l.val = sum\n                sum = 0\n            else:\n                sum += r.val\n            r = r.next\n        \n        l.next = None\n        return head.next\n```\nIf you found this helpful, please upvote! \uD83D\uDC4D\n![main-qimg-a645ae706f7acacc929d906ca22011cd-lq.jpg](https://assets.leetcode.com/users/images/bae75159-f582-46d4-95b1-b9bfd1f6da65_1720057203.2084172.jpeg)\n
['Python3']