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.
思路:链表的基本操作,就地合并有序链表
代码:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *p=l1;
ListNode *q=l2;
ListNode *newHead;
if(l1->val<l2->val)
{
newHead=l1;
p=p->next;
}
else
{
newHead=l2;
q=q->next;
}
ListNode *pre=newHead;
while(p!=NULL && q!=NULL)
{
if(p->val < q->val)
{
pre->next=p;
pre=p;
p=p->next;
}
else
{
pre->next=q;
pre=q;
q=q->next;
}
}
if(p == NULL)
{
pre->next=q;
}
if(q == NULL)
{
pre->next=p;
}
return newHead;
}