-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-6-flatten-a-linked-list.cpp
More file actions
62 lines (53 loc) · 1.24 KB
/
Copy pathDay-6-flatten-a-linked-list.cpp
File metadata and controls
62 lines (53 loc) · 1.24 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
/*
* Definition for linked list.
* class Node {
* public:
* int data;
* Node *next;
* Node *child;
* Node() : data(0), next(nullptr), child(nullptr){};
* Node(int x) : data(x), next(nullptr), child(nullptr) {}
* Node(int x, Node *next, Node *child) : data(x), next(next), child(child) {}
* };
*/
Node* merge(Node* l1, Node* l2){
Node *a = l1, *b = l2, *dummy = new Node(-1);
Node* ans = dummy;
while(a && b){
if(a->data < b->data){
dummy->child = a;
dummy = dummy->child;
a = a->child;
}else{
dummy->child = b;
dummy = dummy->child;
b = b->child;
}
}
if(a){
dummy->child = a;
}else{
dummy->child = b;
}
return ans->child;
}
Node* solve(Node* head){
if(head==NULL) return NULL;
if(head->next){
// next is present --> requires new connection arrangements
// get the next_node
Node* next_node = head->next;
// get the flattened_next list
Node* flattened_next = solve(next_node);
// make connections of current list with flattened_next
head->next = NULL;
// basically merge two sorted lists
return merge(head, flattened_next);
}
return head;
}
Node* flattenLinkedList(Node* head)
{
// assuming solve() --> returns a flattened list provided we pass it a head pointer
return solve(head);
}