|
| 1 | +/*You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. |
| 2 | +Number of nodes in a linked-list can be 0. |
| 3 | +Merge all the linked-lists into one sorted linked-list and return it. |
| 4 | +*/ |
| 5 | + |
| 6 | +#include <bits/stdc++.h> |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +struct ListNode |
| 10 | +{ |
| 11 | + int val; |
| 12 | + ListNode *next; |
| 13 | + ListNode(int n) |
| 14 | + { |
| 15 | + val = n; |
| 16 | + next = NULL; |
| 17 | + } |
| 18 | +}; |
| 19 | + |
| 20 | +void printList(ListNode* head){ |
| 21 | + int i = 0; |
| 22 | + while(head){ |
| 23 | + cout<<head->val<<" "; |
| 24 | + head = head->next; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +//Go on merging 2 linked list into 1 |
| 29 | +ListNode* mergeTwoLists(ListNode* l1,ListNode* l2) { |
| 30 | + if(!l1) return l2; |
| 31 | + if(!l2) return l1; |
| 32 | + if(l1->val<l2->val){ |
| 33 | + l1->next=mergeTwoLists(l1->next,l2); |
| 34 | + return l1; |
| 35 | + } |
| 36 | + else{ |
| 37 | + l2->next=mergeTwoLists(l1,l2->next); |
| 38 | + return l2; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | +ListNode* mergeKLists(vector<ListNode*>& lists) { |
| 44 | + if(!lists.size()) return NULL; |
| 45 | + int l=lists.size(); |
| 46 | + while(l>1){ |
| 47 | + for(int i=0;i<l/2;i++){ |
| 48 | + //Passing 2 linked-list head to merge them |
| 49 | + lists[i]=mergeTwoLists(lists[i],lists[l-1-i]); |
| 50 | + } |
| 51 | + l=(l+1)/2; |
| 52 | + } |
| 53 | + return lists.front(); |
| 54 | +} |
| 55 | + |
| 56 | +int main() |
| 57 | +{ |
| 58 | + int NumOfList, NumOfNodes, nl, nn, data; |
| 59 | + vector<ListNode*> headList; |
| 60 | + //cout<<"Enter no of list\n"; |
| 61 | + cin>>NumOfList; |
| 62 | + nl = NumOfList; |
| 63 | + |
| 64 | + while(nl--){ |
| 65 | + //cout<<"Enter no of nodes\n"; |
| 66 | + cin>>NumOfNodes; |
| 67 | + nn = NumOfNodes; |
| 68 | + ListNode* head = NULL; |
| 69 | + ListNode* tail = head; |
| 70 | + int i = NumOfNodes; |
| 71 | + while(nn--){ |
| 72 | + cin>>data; |
| 73 | + if(nn == NumOfNodes-1){ |
| 74 | + head = new ListNode(data); |
| 75 | + tail = head; |
| 76 | + } |
| 77 | + else{ |
| 78 | + tail->next = new ListNode(data); |
| 79 | + tail = tail->next; |
| 80 | + } |
| 81 | + |
| 82 | + } |
| 83 | + headList.push_back(head); |
| 84 | + } |
| 85 | + ListNode* finalHead = mergeKLists(headList); |
| 86 | + printList(finalHead); |
| 87 | + return 0; |
| 88 | +} |
| 89 | +//No extra space used. |
| 90 | + |
0 commit comments