Home [Medium] Merge Nodes in Between Zeros
Post
Cancel

[Medium] Merge Nodes in Between Zeros

‘Merge Nodes in Between Zeros (Medium)`


📌 Problem

https://leetcode.com/problems/merge-nodes-in-between-zeros/

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeNodes(ListNode head) {

        ListNode result = new ListNode(0);
        ListNode resultNode = result;
        
        int sum = 0;
        while (head.next != null) {
            head = head.next;

            if (head.val != 0) sum += head.val;
            else {
                result.val = sum;
                if (head.next != null) {
                    result.next = new ListNode(0);
                    result = result.next;
                }
                sum = 0;
            }
        }

        return resultNode;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public ListNode mergeNodes(ListNode head) {
        ListNode dummy = new ListNode(Integer.MIN_VALUE), prev = dummy;
        while (head != null && head.next != null) {
            prev.next = head; // prev connects next 0 node.
            head = head.next; // head forward to a non-zero node.
            
            while (head != null && head.val != 0) { // traverse all non-zero nodes between two zero nodes.
                prev.next.val += head.val; // add current value to the previous zero node.
                head = head.next; // forward one step.
            }
            prev = prev.next; // prev point to the summation node (initially 0).
        }
        prev.next = null; // cut off last 0 node.

        return dummy.next;
    }
}

This post is licensed under CC BY 4.0 by the author.

[Medium] Merge In Between Linked Lists

[Medium] Sort List

Comments powered by Disqus.