From 994f837c612ba5df553100eb2754e2811bad5fc2 Mon Sep 17 00:00:00 2001 From: Rishabh Pandey <115353162+rishabhpandey30@users.noreply.github.com> Date: Sat, 8 Nov 2025 16:48:14 +0530 Subject: [PATCH] Implement merge function for k sorted lists add the leetcode problem no. 23 --- Merge_k_Sorted_Lists.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Merge_k_Sorted_Lists.cpp diff --git a/Merge_k_Sorted_Lists.cpp b/Merge_k_Sorted_Lists.cpp new file mode 100644 index 00000000..d322d830 --- /dev/null +++ b/Merge_k_Sorted_Lists.cpp @@ -0,0 +1,46 @@ +/** + * 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* merge(ListNode* l1, ListNode* l2){ + ListNode* ans = new ListNode(-1); + ListNode* temp = ans; + while(l1!=NULL && l2!=NULL){ + if(l1->val >l2->val){ + temp->next = l2; + temp =l2; + l2= l2->next; + } + else{ + temp->next = l1; + temp =l1; + l1= l1->next; + } + } + if(l1){ + temp->next = l1; + } + if(l2){ + temp->next = l2; + } + return ans->next; + } + ListNode* mergeKLists(vector& lists) { + if(lists.size()==0){ + return NULL; + } + ListNode* head = lists[0]; + for(int i=1;i