Skip to content

Commit c0bf515

Browse files
Update 4th July code
1 parent dc35b58 commit c0bf515

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Intuition
2+
This function processes a linked list where segments between consecutive zeroes are summed into new nodes. It starts iterating from the second node (head->next) to skip the initial zero. As it traverses, it accumulates values (c) until it encounters a zero, then creates a new node with the accumulated sum. The resulting linked list consists of these summed nodes, effectively merging segments of nodes between zeroes into single nodes with their aggregated values.
3+
4+
Approach
5+
Initialization:
6+
temp starts at head->next to skip the initial zero.
7+
ans is a new dummy node to construct the result list.
8+
tempAns points to the dummy node, used to build the result list.
9+
c is a counter to sum the values between zeroes.
10+
Traversal and Summation:
11+
Traverse the linked list using temp.
12+
If temp is not zero, add its value to c.
13+
If temp is zero, create a new node with the value c and add it to the result list. Then, reset c to zero.
14+
Construction of the Result List:
15+
For each segment of values between zeroes, create a new node and link it to the result list.
16+
Continue this until the end of the original list.
17+
The result list is built starting from ans->next to skip the dummy node.
18+
19+
Complexity
20+
Time complexity:
21+
O(n)
22+
23+
Space complexity:
24+
O(1)
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
6+
struct ListNode
7+
{
8+
int val;
9+
ListNode *next;
10+
ListNode() : val(0), next(nullptr){}
11+
ListNode(int x) : val(x), next(nullptr){}
12+
ListNode(int x, ListNode *next) : val(x), next(next){}
13+
};
14+
15+
class Solution
16+
{
17+
public:
18+
ListNode *mergeNodes(ListNode *head)
19+
{
20+
ListNode *temp = head->next;
21+
ListNode *ans = new ListNode(-1);
22+
ListNode *tempAns = ans;
23+
int c = 0;
24+
while (temp)
25+
{
26+
if (temp and temp->val != 0)
27+
{
28+
c += temp->val;
29+
}
30+
else if (temp and temp->val == 0)
31+
{
32+
ListNode *t = new ListNode(c);
33+
tempAns->next = t;
34+
tempAns = tempAns->next;
35+
c = 0;
36+
}
37+
temp = temp->next;
38+
}
39+
return ans->next;
40+
}
41+
};

0 commit comments

Comments
 (0)