My solution:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *retList = NULL, *tempList = NULL;
if(!l1 && !l2) return retList;
int val = 0, val1 = 0, val2 = 0;
retList = tempList = new ListNode(0);
while(l1 || l2){
val1 = l1?l1->val:0;
val2 = l2?l2->val:0;
if(((val1<val2) && l1) || !l2){
tempList->val = val1;
if(!(l1->next) && !l2) return retList;
tempList->next = new ListNode(0);
tempList = tempList->next;
l1 = (l1->next)?l1->next:NULL;
continue;
}
else{
tempList->val = val2;
if(!(l2->next) && !l1) return retList;
tempList->next = new ListNode(0);
tempList = tempList->next;
l2 = (l2->next)?l2->next:NULL;
continue;
}
}
return retList;
}
Other Guy's solution:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if(!l1) // If no l1, return l2
return l2;
if(!l2) // If no l2, return l1
return l1;
if(!l2 && !l1) // If neither, return NULL;
return NULL;
ListNode* head; // The pointer we will use to construct a merged list
if(l1->val < l2->val) // If l1 less than l2
{
head = l1; // We start at l1
l1 = l1->next; // and iterate l1
}
else // If l2 less than l1
{
head = l2; // We start at l2
l2 = l2->next; // and iterate l2
}
ListNode* ret = head; // We need to save the addres of the head of the list
while(l1 && l2) // While both input lists have values
{
if(l1->val < l2->val) // Compare the current values, if l1 is less
{
head->next = l1; // Append the merged list with l1's current address
l1 = l1->next; // Advance l1
}
else // Else, l2 had the low value
{
head->next = l2; // Append l2 to the list
l2 = l2->next; // Advance l2
}
head->next->next = NULL; // Append a NULL teminator to the list
head = head->next; // Advance the merged list
}
// Lastly, if list were different lengths, we need to append the longer list tail to the merged list
if(l1)
head->next = l1;
else if(l2)
head->next = l2;
return ret; // Return the starting address of head that we saved.
}