-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-6-flatten-a-multilevel-doubly-linked-list.cpp
49 lines (41 loc) · 1.29 KB
/
Day-6-flatten-a-multilevel-doubly-linked-list.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
Node* solve(Node* head){
if(head == NULL) return NULL;
if(head->child){
// child present --> make new connections
// store next_node
Node* next_node = head->next;
// get flattened_child head
Node* flattened_child = solve(head->child);
// make connections of current node to child node
head->next = flattened_child;
head->child = NULL;
flattened_child->prev = head;
// make connections of next node to child node
while(flattened_child->next) flattened_child = flattened_child->next;
flattened_child->next = next_node;
if(next_node){
next_node->prev = flattened_child;
}
}
// call for next node in the list
solve(head->next);
return head;
}
Node* flatten(Node* head) {
// best solution will be to do a recursive approach since child can have child and so on...
// hypothesis: solve() --> assuming we pass the head of a node and it returns after flattening it
return solve(head);
}
};