I don't understand why I have problems with one test case on the inputs I have — it fails:
Here is my code:
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;
}
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 don't check that neither temp1
nor temp2
is NULL
after you've moved one of them through the list, so your code is likely to crash on if (temp1->val == temp2->val)
when the loop reaches the end of the lists. You should only execute one of three actions in each iteration, 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;
}