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;
}
本文详细介绍了如何使用链表的基本操作合并两个有序链表,并提供了对应的代码实现。通过实例解析,帮助开发者掌握链表合并技巧。
1463

被折叠的 条评论
为什么被折叠?



