I am trying to solve the merge k sorted lists question on leetcode using the non-recursive solution. When I run the code it gives the error as mentioned below. Can you help me to solve the problem? Error is at lists[min_idx] = lists[min_idx]->next;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
struct ListNode *result;
result = (struct ListNode *)malloc(sizeof(struct ListNode));
result = NULL;
struct ListNode *p;
if (!listsSize){
return result;
}
int min = INT_MAX;
int min_idx = 0;
int cnt=0;
while (lists){
for ( int i = 0 ; i<listsSize ; i++){
if (lists[i]){
cnt=0;
if (lists[i]->val < min){
min = lists[i]->val;
min_idx = i;
}
}
else {
cnt++;
}
}
if (cnt==listsSize){
break;
}
struct ListNode *temp;
temp = (struct ListNode *)malloc(sizeof(struct ListNode));
temp->val = min;
temp->next = NULL;
if (result == NULL){
result = temp;
p = temp;
}
else {
p->next = temp;
p = p->next;
}
lists[min_idx] = lists[min_idx]->next;
}
return result;
}
ERROR:
Line 52: Char 40: runtime error: member access within null pointer of type 'struct ListNode' [solution.c].