-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path036 Flatten A Linked List.cpp
55 lines (49 loc) · 1.28 KB
/
036 Flatten A 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
50
51
52
53
54
55
/*
* 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) {}
* };
*/
// used mergesort technique
Node* mergeLL(Node* head1, Node* head2){
if(head1 == NULL) return head2;
else if(head2 == NULL) return head1;
Node* root = (head1->data > head2->data)?(head2):(head1);
Node* prev = root;
Node* first = root->child;
Node* second = (root == head1)?(head2):(head1);
while(first != NULL && second != NULL){
if(first->data < second->data){
prev->child = first;
prev = first;
first = first->child;
}
else{
prev->child = second;
prev = second;
second = second->child;
}
}
if(first != NULL){
prev->child = first;
}
else if(second != NULL){
prev->child = second;
}
return root;
}
Node* flattenLinkedList(Node* head)
{
if(head == NULL || head->next == NULL) return head;
Node* root = head->next;
head->next = NULL;
root = flattenLinkedList(root);
head = mergeLL(head, root);
return head;
}