-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathAnswer36.cpp
38 lines (35 loc) · 891 Bytes
/
Answer36.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
//Flattening a Linked List (C++)
//Time Complexity: O(n*m)
//Space Complexity: O(1)
Node* merge(Node* root,Node* root_next){
Node* current=new Node(-1);
Node* temp=current;
while(root!=NULL&&root_next!=NULL){
if(root->data<=root_next->data){
current->bottom=root;
current=current->bottom;
root=root->bottom;
}
else{
current->bottom=root_next;
current=current->bottom;
root_next=root_next->bottom;
}
if(root==NULL){
current->bottom=root_next;
}
else if(root_next==NULL){
current->bottom=root;
}
}
return temp->bottom;
}
Node *flatten(Node *root)
{
if(root==NULL || root->next==NULL){
return root;
}
root->next=flatten(root->next);
root=merge(root,root->next);
return root;
}