2181 - Merge Nodes in Between Zeros
JAVA
class Solution {
public ListNode mergeNodes(ListNode head) {
ListNode dummy = new ListNode();
int s = 0;
ListNode tail = dummy;
for (ListNode cur = head.next; cur != null; cur = cur.next) {
if (cur.val != 0) {
s += cur.val;
} else {
tail.next = new ListNode(s);
tail = tail.next;
s = 0;
}
}
return dummy.next;
}
}C++
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode dummy, *tail = &dummy;
while (head) {
if (head->val == 0) head = head->next; // skip leading `0`
if (!head) break;
int sum = 0;
while (head->val != 0) { // sum numbers before the next `0`
sum += head->val;
head = head->next;
}
tail->next = new ListNode(sum); // append `sum`
tail = tail->next;
}
return dummy.next;
}
};
Comments
Post a Comment