-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaily17.cpp
More file actions
85 lines (79 loc) · 2.23 KB
/
Copy pathdaily17.cpp
File metadata and controls
85 lines (79 loc) · 2.23 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Solution 1
/**
* 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) {
auto zeroes = std::vector<int>{};
auto total = int{0};
auto new_head = new ListNode();
auto prev = new ListNode();
auto merged = 0;
while (head != nullptr) {
if (head->val == 0) {
zeroes.push_back(0);
if (zeroes.size() == 2) {
zeroes.clear();
zeroes.push_back(0);
// std::cout << total << std::endl;
auto node = new ListNode(total);
if (new_head->val == 0) {
new_head = node;
}
prev->next = node;
prev = prev->next;
if (merged == 1) {
new_head->next = prev;
}
merged++;
total = 0;
}
} else
total += head->val;
head = head->next;
}
return new_head;
}
};
// Solution 2
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode* ret = nullptr;
ListNode* curr = nullptr;
int sum = 0;
while(head != nullptr){
if(head->val == 0){
if(sum == 0){
head = head->next;
continue;
}
ListNode* node = new ListNode(sum);
if(curr == nullptr){
curr = node;
ret = node;
head = head->next;
sum = 0;
continue;
}
curr->next = node;
curr = node;
head = head->next;
sum = 0;
continue;
}
int x = head->val;
sum = sum + x;
head = head->next;
}
return ret;
}
};