Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
41 lines (39 sloc) 866 Bytes
problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
-------------------------------------------------------------------------
solution:
此题是链表的归并排序基础版
////////////////////////////
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(l1 == NULL)
return l2;
else if(l2 == NULL)
return l1;
ListNode *proot = NULL;
ListNode **ptail = &proot;
while(l1 && l2)
{
ListNode *minNode;
if(l1->val < l2->val)
{
minNode = l1;
l1 = l1->next;
}
else
{
minNode = l2;
l2 = l2->next;
}
*ptail = minNode;
ptail = &(minNode->next);
}
ListNode *lremain = l1 ? l1 : l2;
while(lremain)
{
*ptail = lremain;
ptail = &(lremain->next);
lremain = lremain->next;
}
return proot;
}