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.
注意:本题中给的两个链表没有头指针,有头指针的链表结构和没有头指针的链表差别在,有头指针的链表在插入删除时,所有的操作是一样的,相反,没有头指针的,第一个节点操作跟后面的节点是不一样的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode *head=NULL;
if(l1->val<l2->val)
{
head=l1;
l1=l1->next;
}
else
{
head=l2;
l2=l2->next;
}
ListNode *p=head;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<l2->val)
{
p->next=l1;
p=l1;
l1=l1->next;
}
else
{
p->next=l2;
p=l2;
l2=l2->next;
}
}
if(l1==NULL)
p->next=l2;
if(l2==NULL)
p->next=l1;
return head;
}
};