-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmerge_k_sorted_lists.c
45 lines (42 loc) · 1.01 KB
/
merge_k_sorted_lists.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//psuedo code
struct ListNode* mergeTwoLists(struct ListNode*list1,struct ListNode*list2)
{
struct ListNode*head=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode*cur=head;
while(list1 && list2)
{
if(list1->val > list2->val)
{
cur->next=list2;
list2=list2->next;
}
else
{
cur->next=list1;
list1=list1->next;
}
cur=cur->next;
}
if(list1){
cur->next=list1;
}
else{
cur->next=list2;
}
cur=head->next;
free(head);
return cur;
}
struct ListNode* merge(struct ListNode**lists,int beg,int end)
{
if(beg>end) return NULL;
if(beg==end) return lists[beg];
int mid=(beg+end)/2;
struct ListNode*left=merge(lists,beg,mid);
struct ListNode*right=merge(lists,mid+1,end);
return mergeTwoLists(left,right);
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
return merge(lists,0,listsSize-1);
}
//psuedo code ends