Leetcode 23 Merge k Sorted Lists Solution in c++ | Hindi Coding Community

0

 


You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it. 


Example 1:


Input: lists = [[1,4,5],[1,3,4],[2,6]]

Output: [1,1,2,3,4,4,5,6]

Explanation: The linked-lists are:

[

  1->4->5,

  1->3->4,

  2->6

]

merging them into one sorted list:

1->1->2->3->4->4->5->6

Example 2:


Input: lists = []

Output: []

Example 3:


Input: lists = [[]]

Output: []



class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int count =0;
for(auto it : lists){
if(it == NULL)count++;
}
if(count == lists.size())return NULL;
vector<int> v;
for(auto it : lists){
while(it!=NULL){
v.push_back(it->val);
it = it->next;
}
}
sort(v.begin(), v.end());
ListNode* a = new ListNode(v[0]);
ListNode * b = a;
for(int i = 0; i<v.size()-1; i++){
b->next = new ListNode(v[i+1]);
b = b->next;
}
return a;
}
};

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !