Skip to content

Commit

Permalink
Problem 23 in leetcode in C language
Browse files Browse the repository at this point in the history
  • Loading branch information
BRAGADEESH2005 committed Oct 31, 2023
1 parent e5dad3f commit fd2a825
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions leetcode/src/23.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
if(listsSize > 1 ){

struct ListNode *p1 = lists[0];
struct ListNode *p2 = NULL;
struct ListNode *third = NULL,*last = NULL;
for(int i=1;i<listsSize;i++)
{
p2 = lists[i];
if(p2 && p1)
{ if (p1->val < p2->val){
third = last = p1;
p1=p1->next;
last->next = NULL;
}else{
third = last = p2;
p2=p2->next;
last->next = NULL;
}
while(p1 != NULL && p2!= NULL){
if(p1->val <p2->val){
last ->next = p1;
last = p1;
p1=p1->next;
last->next = NULL;
}else{
last ->next = p2;
last = p2;
p2=p2->next;
last->next = NULL;
}
}

if (p1 ==NULL){
last ->next = p2;
}else{
last ->next=p1;
}
p1=third;
}
else if (p1==NULL){
p1=p2;
}}
return p1;
}else{
return (listsSize == 0)?NULL:lists[0];
}

}

0 comments on commit fd2a825

Please sign in to comment.