-
Notifications
You must be signed in to change notification settings - Fork 3
/
2181.cpp
35 lines (35 loc) · 911 Bytes
/
2181.cpp
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
35
/**
* 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) {
vector<int> v;
int accum = 0;
while (head) {
if (head->val == 0) {
v.push_back(accum);
accum = 0;
}
else {
accum += head->val;
}
head = head->next;
}
ListNode* sentinel = new ListNode(0);
ListNode* current = sentinel;
int n = v.size();
for (int i = 1; i < n; ++i) {
current->next = new ListNode(v[i]);
current = current->next;
}
return sentinel->next;
}
};