Seamless Node Merging Between Zeros in Linked Lists
Intuition\nThe intuition behind this solution is to traverse the linked list and accumulate the sum of node values between two consecutive 0s. Each time a secon
# Intuition\nThe intuition behind this solution is to traverse the linked list and accumulate the sum of node values between two consecutive 0s. Each time a second 0 is encountered, the accumulated sum is assigned to the node following the first 0, effectively merging the nodes between them. The process continues until the entire list is processed, and all 0s are removed, leaving only the merged sums. This approach ensures efficient in-place modification of the linked list.\n\n# Approach\nTraverse the linked list while accumulating values between two consecutive 0s. When the second 0 is encountered, store the accumulated sum in the previous node and reset the sum. Continue this process, updating the list in place, and remove the 0s at the end.\n\n# Complexity\n- Time complexity:\nThe time complexity is O(n), where n is the number of nodes in the linked list.\n\n- Space complexity:\nThe space complexity is O(1), as no additional data structures are used apart from a few variables for tracking the sum and pointers.\n\n# Code\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNode() {}\n *     ListNode(int val) { this.val = val; }\n *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public ListNode mergeNodes(ListNode head) {\n        ListNode temp=head;\n        ListNode temp1=head;\n        ListNode prev=head;\n        int sum=0,zero=0;\n        while(temp!=null)\n        {\n            if(temp.val==0)\n            {\n                zero++;\n            }\n            if(zero==1)\n            {\n                sum=sum+temp.val;\n            }\n            else if(zero==2)\n            {\n                temp1.val=sum;\n                sum=0;\n                zero=1;\n                prev=temp1;\n                temp1=temp1.next;\n            }\n            temp=temp.next;\n        }\n        prev.next=null;\n        return head;\n    }\n}\n```
['Java']