分析:新开一个链表 l3,作为结果记录的链表,再开一个链表指针cur用于操作 l3。合并的时候先将两个链表指向的下一个数进行比较,把较小的插到 l3中。最后,把 l1或 l2未合并的部分放到结果链表表尾。另加一个判断语句,在进入函数的时候就判断有没有空链表,如果有,就直接返回另外一个链表。
/**
* 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;
else if(l2==NULL)
return l1;
ListNode *l3=new ListNode(0),*cur=l3;
while(l1&&l2)
{
if(l1->val < l2->val)
{
cur->next=l1;
l1=l1->next;
}
else
{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
cur->next=l1?l1:l2;
return l3->next;
}
};//Runtime: 8 ms,Memory Usage: 8.8 MB