Using a dummy node to add the lesser node of list l1 and list l2. At the end returning the location pointing next to the dummy node to get the actual merged sorted list but getting a runtime load of address with insufficient space for an object of type struct ListNode at return dummyNode->next.
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL && l2 != NULL) {
return l2;
}
if (l1 != NULL && l2 == NULL) {
return l1;
}
struct ListNode *dummyNode = NULL;
struct ListNode *head = NULL;
dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode *));
head = dummyNode;
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
head->next = l1;
l1 = l1->next;
head = head->next;
}
else {
head->next = l2;
l2 = l2->next;
head = head->next;
}
}
if (l1 != NULL) {
head->next = l1;
}
if (l2 != NULL) {
head->next = l2;
}
return dummyNode->next;
}
sizeof(struct ListNode)instead ofsizeof(struct ListNode *)dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode));writedummyNode = (struct ListNode *)malloc(sizeof(*dummyNode));which is less error prone. You even can drop the cast :dummyNode = malloc(sizeof(*dummyNode));