[LeetCode] Merge Nodes in Between Zeros

2181. Merge Nodes in Between Zeros

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.

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode* cur = head;
while(cur->next) {
if(cur->next->val == 0) {
if(cur->next->next) {
cur = cur->next;
} else {
cur->next = NULL;
}
} else {
cur->val += cur->next->val;
cur->next = cur->next->next;
}
}
return head;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/20/PS/LeetCode/merge-nodes-in-between-zeros/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.