题目: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) return l2;
if(!l2) return l1;
ListNode * head=l1; //把1一直当做新头结点
ListNode * pre=NULL;
while(l1 !=NULL && l2 !=NULL)
{
if( l2->val < l1->val ) //2比1小,就要插到前面
{
ListNode *tmp=l2->next;
l2->next=l1;
if(pre ==NULL) head=l2; //如果1是头结点,更新头
else pre->next=l2; //加入2
pre=l2; //1后移一位
l2=tmp; //2后移一位
}
else
{
pre=l1;
l1=l1->next; //2的点比1的大,直接1右移
}
}
if(l1 ==NULL && l2 !=NULL) //跳出循环说明2后面的都比1大,直接接在后面
pre->next=l2;
return head;
}