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.
题目就是合并两个有序的链表,具体方法就是:直接操作两个链表的各个指针域,使得最后两个链表连成一个有序的链表即可,其中主要用到了3个指针,p,cur1,cur2
/**
* 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) {
ListNode *p,*cur1,*cur2,*res;
if(NULL==l1)//特殊情况
return l2;
else if(NULL==l2)//特殊情况
return l1;
else//一般情况
{
cur1=l1;
cur2=l2;
if((*cur1).val<(*cur2).val)
{
p=cur1;
cur1=cur1->next;
}
else
{
p=cur2;
cur2=cur2->next;
}
res=p;//保存头结点,备份用于返回
while(cur1!=NULL && cur2!=NULL)
{
if((*cur1).val<(*cur2).val)
{
p->next=cur1;
cur1=cur1->next;
}
else
{
p->next=cur2;
cur2=cur2->next;
}
p=p->next;
}
if(cur1==NULL)
p->next=cur2;
else
p->next=cur1;
}
return res;
}
};