Skip to content

Instantly share code, notes, and snippets.

@eariassoto
Created July 17, 2016 15:38
Show Gist options
  • Save eariassoto/34090ddc955864be4ce6b0f947594f84 to your computer and use it in GitHub Desktop.
Save eariassoto/34090ddc955864be4ce6b0f947594f84 to your computer and use it in GitHub Desktop.
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *newList = NULL, *newTail = NULL;
while(l1 != NULL && l2 != NULL)
{
ListNode *newNext = (l1->val < l2->val) ? l1 : l2;
if(newList == NULL)
{
newList = newNext;
newTail = newNext;
}
else
{
newTail->next = newNext;
newTail = newNext;
}
if(newNext == l1)
l1 = l1->next;
else
l2 = l2->next;
}
if(l1 != NULL)
{
if(newList == NULL)
newList = l1;
else
newTail->next = l1;
}
if(l2 != NULL)
{
if(newList == NULL)
newList = l2;
else
newTail->next = l2;
}
return newList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment