0% found this document useful (0 votes)
23 views1 page

Merge K Sorted Lists

The document defines a C++ class 'Solution' that contains methods for merging two linked lists and merging multiple linked lists. The 'mergeTwoLists' method combines two sorted linked lists into one sorted linked list, while the 'mergeKLists' method merges 'k' sorted linked lists by repeatedly merging pairs of lists. Two approaches for merging the lists are provided, one using a temporary result node and another using a vector to manage the lists dynamically.

Uploaded by

Ayush Saklani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views1 page

Merge K Sorted Lists

The document defines a C++ class 'Solution' that contains methods for merging two linked lists and merging multiple linked lists. The 'mergeTwoLists' method combines two sorted linked lists into one sorted linked list, while the 'mergeKLists' method merges 'k' sorted linked lists by repeatedly merging pairs of lists. Two approaches for merging the lists are provided, one using a temporary result node and another using a vector to manage the lists dynamically.

Uploaded by

Ayush Saklani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

/**

* Definition for singly-linked list.


* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode * res = new ListNode();
ListNode * temp = res;
while(list1!=NULL && list2!=NULL){
if(list1->val <= list2->val){
temp->next=list1;
list1=list1->next;
}
else{
temp->next=list2;
list2=list2->next;
}
temp=temp->next;
}
if(list2!=NULL){
temp->next=list2;
}
else if(list1!=NULL){
temp->next=list1;
}
return res->next; // first node is temporary and it will be empty
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0) return NULL;
ListNode * res = lists[0];
for(int i = 1; i < lists.size(); i++){
res = mergeTwoLists(res,lists[i]);
}
return res;
}
};

// approach 2
// since we are adding the value in the same array it is time consuming we can use
this method in which we take 2 different string at a
// given time

ListNode* mergeKLists(vector<ListNode*>& lists) {


if(lists.empty()) return nullptr;
while(lists.size() > 1){
lists.push_back(mergeTwoLists(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}

You might also like