将两个升序链表合并成一个升序链表,新链表是给定两个链表的节点组成的
递归
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
if(NULL==l1) return l2;
if(NULL==l2) return l1;
if(l1->val<=l2->val)
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
非递归
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
if(NULL==l1&&NULL==l2) return NULL;
if(NULL==l1&&NULL!=l2) return l2;
if(NULL==l2&&NULL!=l1) return l1;
struct ListNode* p=l1;
struct ListNode* q=l2;
struct ListNode* head=NULL;//生成新的链表的头指针
if(p->val<=q->val)//先确定头指针指向哪一个
{
head=p;
p=p->next;
}
else
{
head=q;
q=q->next;
}
struct ListNode* s=head;//始终指向最后一个节点
while(p&&q)
{
if(p->val<=q->val)//最后一个节点指向小的那一个节点
{
s->next=p;
s=p;
p=p->next;
}
else
{
s->next=q;
s=q;
q=q->next;
}
}
if(p!=NULL)
{
s->next=p;
}
if(q!=NULL)
{
s->next=q;
}
return head;
}