Skip to content

Commit f09c590

Browse files
authored
Time complexity: O(n), Space complexity: O(1)
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list. Example 1: Input: head = [0,3,1,0,4,5,2,0] Output: [4,11] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 3 + 1 = 4. - The sum of the nodes marked in red: 4 + 5 + 2 = 11. Example 2: Input: head = [0,1,0,3,0,2,2,0] Output: [1,3,4] Explanation: The above figure represents the given linked list. The modified list contains - The sum of the nodes marked in green: 1 = 1. - The sum of the nodes marked in red: 3 = 3. - The sum of the nodes marked in yellow: 2 + 2 = 4.
1 parent 9ef8828 commit f09c590

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

2181. Merge Nodes in Between Zeros

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
public class Solution {
12+
13+
public ListNode mergeNodes(ListNode head) {
14+
// Initialize a sentinel/dummy node with the first non-zero value.
15+
ListNode current = head.next;
16+
ListNode nextSum = current;
17+
18+
while (nextSum != null) {
19+
int sum = 0;
20+
// Find the sum of all nodes until you encounter a 0.
21+
while (nextSum.val != 0) {
22+
sum += nextSum.val;
23+
nextSum = nextSum.next;
24+
}
25+
26+
// Assign the sum to the current node's value.
27+
current.val = sum;
28+
// Move nextSum to the first non-zero value of the next block.
29+
nextSum = nextSum.next;
30+
// Move current also to this node.
31+
current.next = nextSum;
32+
current = current.next;
33+
}
34+
return head.next;
35+
}
36+
}

0 commit comments

Comments
 (0)