|
| 1 | +// Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers: |
| 2 | +// (i) a next pointer to the next node, |
| 3 | +// (ii) a bottom pointer to a linked list where this node is head. |
| 4 | +// Each of the sub-linked-list is in sorted order. |
| 5 | +// Flatten the Link List such that all the nodes appear in a single level while maintaining the sorted order. |
| 6 | +// Note: The flattened list will be printed using the bottom pointer instead of next pointer. |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +// Example 1: |
| 11 | + |
| 12 | +// Input: |
| 13 | +// 5 -> 10 -> 19 -> 28 |
| 14 | +// | | | | |
| 15 | +// 7 20 22 35 |
| 16 | +// | | | |
| 17 | +// 8 50 40 |
| 18 | +// | | |
| 19 | +// 30 45 |
| 20 | +// Output: 5-> 7-> 8- > 10 -> 19-> 20-> |
| 21 | +// 22-> 28-> 30-> 35-> 40-> 45-> 50. |
| 22 | +// Explanation: |
| 23 | +// The resultant linked lists has every |
| 24 | +// node in a single level. |
| 25 | +// (Note: | represents the bottom pointer.) |
| 26 | + |
| 27 | + |
| 28 | +// Example 2: |
| 29 | + |
| 30 | +// Input: |
| 31 | +// 5 -> 10 -> 19 -> 28 |
| 32 | +// | | |
| 33 | +// 7 22 |
| 34 | +// | | |
| 35 | +// 8 50 |
| 36 | +// | |
| 37 | +// 30 |
| 38 | +// Output: 5->7->8->10->19->20->22->30->50 |
| 39 | +// Explanation: |
| 40 | +// The resultant linked lists has every |
| 41 | +// node in a single level. |
| 42 | + |
| 43 | +// (Note: | represents the bottom pointer.) |
| 44 | + |
| 45 | +// Expected Time Complexity: O(N*M) |
| 46 | +// Expected Auxiliary Space: O(1) |
| 47 | + |
| 48 | +// Company Tags |
| 49 | +// Innovation Labs Amazon Drishti-Soft Flipkart Goldman Sachs Microsoft Paytm Payu Qualcomm Snapdeal Visa |
| 50 | + |
| 51 | +/* Node structure used in the program |
| 52 | +
|
| 53 | +struct Node{ |
| 54 | + int data; |
| 55 | + struct Node * next; |
| 56 | + struct Node * bottom; |
| 57 | +
|
| 58 | + Node(int x){ |
| 59 | + data = x; |
| 60 | + next = NULL; |
| 61 | + bottom = NULL; |
| 62 | + } |
| 63 | +
|
| 64 | +}; |
| 65 | +*/ |
| 66 | + |
| 67 | +/* Function which returns the root of |
| 68 | + the flattened linked list. */ |
| 69 | +Node *flatten(Node *root) |
| 70 | +{ |
| 71 | + vector<int>s; |
| 72 | + Node* secroot = root; |
| 73 | + while(secroot){ |
| 74 | + Node* temp = secroot; |
| 75 | + while(temp){ |
| 76 | + s.push_back(temp->data); |
| 77 | + temp = temp->bottom; |
| 78 | + } |
| 79 | + secroot = secroot->next; |
| 80 | + } |
| 81 | + sort(s.begin(), s.end()); |
| 82 | + Node* root2 = new Node(0); |
| 83 | + Node* dummy = root2; |
| 84 | + for(auto i: s){ |
| 85 | + Node* n = new Node(i); |
| 86 | + dummy->bottom = n; |
| 87 | + dummy = dummy->bottom; |
| 88 | + } |
| 89 | + return root2->bottom; |
| 90 | + |
| 91 | + |
| 92 | +} |
| 93 | + |
0 commit comments