题目:
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.
翻译:
合并2个已经排序的链表,并且返回一个新的链表。这个新的链表应该由前面提到的2个链表的节点所组成。
分析:
注意头节点的处理,和链表结束(next为null)的处理。以下代码新增了一个头指针,来把头节点的处理和普通节点的处理统一了。(剑指offer也有)
代码:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *head=new ListNode(0);
ListNode*pRoot=head;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<l2->val)
{
pRoot->next=l1;
l1=l1->next;
}
else{
pRoot->next=l2;
l2=l2->next;
}
pRoot=pRoot->next;
}
while(l1!=NULL)
{
pRoot->next=l1;
l1=l1->next;
pRoot=pRoot->next;
}
while(l2!=NULL)
{
pRoot->next=l2;
l2=l2->next;
pRoot=pRoot->next;
}
return head->next;
}