Python | One-Pass Traversal with a Dummy Node
see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n    def mergeNodes(self, head: ListNode) -> ListNode:\n        dummy = ListNode(0)\n     
[see the Successfully Accepted Submission](https://leetcode.com/problems/merge-nodes-in-between-zeros/submissions/1309021924/?envType=daily-question&envId=2024-07-04)\n\n# Code\n```\nclass Solution:\n    def mergeNodes(self, head: ListNode) -> ListNode:\n        dummy = ListNode(0)\n        current_new = dummy\n        current = head.next\n        sum_value = 0\n        \n        while current is not None:\n            if current.val != 0:\n                sum_value += current.val\n            else:\n                if sum_value != 0:\n                    current_new.next = ListNode(sum_value)\n                    current_new = current_new.next\n                    sum_value = 0\n            current = current.next\n        \n        return dummy.next\n\n```\n\n\n## Step-by-Step Approach to Implement the Solution:\n\n1. Initialize a dummy node to help build the new linked list.\n2. Traverse the original linked list:\n   - Use a temporary sum variable to accumulate values between zeros.\n   - When encountering a zero (that is not the first zero), append the accumulated sum to the new linked list and reset the sum.\n3. Return the new linked list starting from the next node of the dummy node (since the dummy node is just a helper).\n\n## Explanation:\n\n### Initialization:\n\n- `dummy`: A dummy node to help build the new linked list.\n- `current_new`: A pointer to the current end of the new linked list.\n- `current`: A pointer to traverse the input linked list, starting from the node after the first zero.\n\n### Traversal and Summing:\n\n- Traverse the input list starting from `head.next` (to skip the initial zero).\n- If the current node\'s value is not zero, add its value to `sum_value`.\n- If the current node\'s value is zero and `sum_value` is not zero, it means we have reached the end of a segment. Create a new node with `sum_value` and append it to the new linked list, then reset `sum_value` to zero.\n\n### Return:\n\n- Return the new linked list starting from `dummy.next`, since `dummy` itself is not part of the new list.\n\nThis solution ensures we only traverse the list once, making it efficient with a time complexity of \\(O(n)\\), where \\(n\\) is the number of nodes in the original list.\n\n\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
['Python3']