2181. Merge Nodes in Between Zeros || INTUITIVE || EASY APPROACH || BEATS 99.77%
\n\n# Intuition\nThe mergeNodes function manipulates a singly-linked list such that consecutive nodes with a value of 0 are merged into a single node that holds
![image.png](https://assets.leetcode.com/users/images/b281fe8f-e64e-40d7-8433-66dc8424001f_1720089906.0604641.png)\n\n# Intuition\nThe mergeNodes function manipulates a singly-linked list such that consecutive nodes with a value of 0 are merged into a single node that holds the sum of all consecutive 0 values encountered. For instance, a sequence 0 -> 1 -> 2 -> 0 -> 4 ->0 would be transformed into 3 -> 4 .\n# Approach\n1. **Initialization:** Start with the first node (head) of the linked list.\n2. **Traversal and Modification:**\nUse a pointer t to iterate through the list starting from head->next.\nMaintain a sum variable to accumulate values of consecutive 0 nodes encountered.\nKeep track of prev to link nodes correctly after merging.\n3. **Iterate through the list:**\nIf t->val is not 0, add it to sum.\nIf t->val is 0, set t->val to sum, link the previous node (prev) to t, update prev to t, and reset sum to 0.\n4. **Final adjustments:**\nAfter the loop ends (t reaches the last node), set prev->next to t and assign t->val to sum.\n5. **Return:** Return head->next, which is the modified list starting from the second node (since the first node might be altered).\n# Complexity\n- Time complexity: **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* mergeNodes(ListNode* head) {\n        ListNode* t = head->next;\n        int sum = 0;\n        ListNode* prev = head;\n        while(t->next != nullptr){\n            if(t->val != 0)\n                sum += t->val;\n            else\n            {\n                t->val = sum;\n                prev->next = t;\n                prev = t;\n                sum = 0;\n            }\n            t=t->next;\n        }\n        prev->next = t;\n        t->val = sum;\n        return head->next;\n    }\n};\n\nstatic const int __ = [](){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    //cout.tie(nullptr);\n    return 0;\n}();\n```
['C++']