Merge Two Sorted List in C

Merge Two Sorted List in C
typescript
Ethan Jackson

test case

i dont understand i have problems with one test case on input i have and it fails

1. list1 = [];

2. list2 = [0];

Please take a look at my solution and give me help with that.

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) { struct ListNode* result = NULL; struct ListNode* temp1 = list1; struct ListNode* temp2 = list2; while(temp1 != NULL && temp2 != NULL){ if(temp1 != NULL && temp2 == NULL){ append(&result, temp1->val); temp1 = temp1->next; } if(temp1 == NULL && temp2 != NULL){ append(&result, temp2->val); temp2 = temp2->next; } if(temp1->val < temp2->val){ append(&result, temp1->val); temp1 = temp1->next; } else{ append(&result, temp2->val); temp2 = temp2->next; } if(temp1->val == temp2->val){ append(&result, temp1->val); append(&result, temp2->val); temp1 = temp1->next; temp2 = temp2->next; } } return result; }

Answer

The top of your loop is:

while(temp1 != NULL && temp2 != NULL){ if(temp1 != NULL && temp2 == NULL){

How many times is temp2 == NULL inside that loop?

You need to move the first two conditions out of the loop you have. You need two loops after the current loop:

while (temp1 != NULL) { append(&result, temp1->val); temp1 = temp1->next; } while (temp2 != NULL) { append(&result, temp2->val); temp2 = temp2->next; }

At most one of those loops will actually run.

You also have problems in the rest of the body of your loop. You should only execute one of three actions. Thus:

struct ListNode *mergeTwoLists(struct ListNode *list1, struct ListNode *list2) { struct ListNode *result = NULL; struct ListNode *temp1 = list1; struct ListNode *temp2 = list2; while (temp1 != NULL && temp2 != NULL) { if (temp1->val < temp2->val) { append(&result, temp1->val); temp1 = temp1->next; } else if (temp1->val > temp2->val) { append(&result, temp2->val); temp2 = temp2->next; } else { assert(temp1->val == temp2->val); append(&result, temp1->val); append(&result, temp2->val); temp1 = temp1->next; temp2 = temp2->next; } } while (temp1 != NULL) { append(&result, temp1->val); temp1 = temp1->next; } while (temp2 != NULL) { append(&result, temp2->val); temp2 = temp2->next; } return result; }

Related Articles