-
Notifications
You must be signed in to change notification settings - Fork 27
/
Flattening a Linked List.cpp
52 lines (37 loc) · 1.33 KB
/
Flattening 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
// Problem Statement: Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers:
// (i) a next pointer to the next node,
// (ii) a bottom pointer to a linked list where this node is head.
// Each of the sub-linked-list is in sorted order.
// Flatten the Link List such that all the nodes appear in a single level while maintaining the sorted order.
// Note: The flattened list will be printed using the bottom pointer instead of the next pointer.
Node* mergeTwoLists(Node* a, Node* b) {
Node *temp = new Node(0);
Node *res = temp;
while(a != NULL && b != NULL) {
if(a->data < b->data) {
temp->bottom = a;
temp = temp->bottom;
a = a->bottom;
}
else {
temp->bottom = b;
temp = temp->bottom;
b = b->bottom;
}
}
if(a) temp->bottom = a;
else temp->bottom = b;
return res -> bottom;
}
Node *flatten(Node *root)
{
if (root == NULL || root->next == NULL)
return root;
// recur for list on right
root->next = flatten(root->next);
// now merge
root = mergeTwoLists(root, root->next);
// return the root
// it will be in turn merged with its left
return root;
}