Problem Description:
Given a Linked List where every node represents a linked list and contains two pointers of its type:
(i) a next pointer to the next node
(ii) abottompointerto a linked list where this node is head.
You have to flatten the linked list to a single linked list which is sorted. For Ex: Shown below is a given linked list
5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45
and after flattening it, the sorted linked listlooks like: 5->7->8->10->19->20->22->28->30->35->40->45->50
The node structure has3fields as mentioned. Anext pointer, abottompointerand a data part.
There are multiple test cases. For each test case, this functionwill be called individually.
Note :All linked listsare sorted.
/* node structure used in the program struct node{ int data; struct node * next; struct node * bottom ; }; */ /* Function which returns the root of the flattened linked list. */ node *flatten(node *root) { // Your code here int mn,lastIdx; bool first=0; node *nodes[55]; node *nNode,*nRoot; node *tmp; int idx=0; nodes[idx]=root; tmp=root->next; while(tmp) { idx=idx+1; nodes[idx]=tmp; tmp=tmp->next; } while(1) { mn=100000; lastIdx=-1; for(int i=0;i<=idx;i++) { if(nodes[i]!=NULL) { if(mn>nodes[i]->data) { lastIdx=i; mn=nodes[i]->data; } } } if(lastIdx==-1) break; if(first==0) { nNode=nodes[lastIdx]; nRoot=nNode; first=1; } else { nNode->bottom=nodes[lastIdx]; nNode=nNode->bottom; } nodes[lastIdx]=nodes[lastIdx]->bottom; } return nRoot; }