题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
过程:
当 l2 小于 l1 并且 head 为空时,将head 和 tail 指向 l2。然后l2 指向它的下一个结点。
l1 小于 l2,tail 下一个结点指向 l1,然后 tail = l1,l1 = l1->next。
以此类推:
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (l1==NULL)
{
return l2;
}
if (l2==NULL)
{
return l1;
}
struct ListNode* head,*tail;
head = tail = NULL;
while (l1 && l2)
{
if (l1->val < l2->val)
{
if (head==NULL)
{
head = tail = l1;
}
else
{
tail->next = l1;
tail = l1;
}
l1 = l1->next;
}
else
{
if (head==NULL)
{
head = tail = l2;
}
else
{
tail->next = l2;
tail = l2;
}
l2 = l2->next;
}
}
if (l1)
{
tail->next = l1;
}
if (l2)
{
tail->next = l2;
}
return head;
}
优化
我们发现在while代码内部有多个类似下面的代码
if (head==NULL)
{
head = tail = l2;
}
可不可以去掉这一段,然后在while前面先统一的处理完,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (l1==NULL)
{
return l2;
}
if (l2==NULL)
{
return l1;
}
struct ListNode* head,*tail;
head = tail = NULL;
//先取一个小的做第一个
if (l1->val < l2->val)
{
head = tail = l1;
l1 = l1->next;
}
else
{
head = tail = l2;
l2 = l2->next;
}
while (l1 && l2)
{
if (l1->val < l2->val)
{
tail->next = l1;
tail = l1;
l1 = l1->next;
}
else
{
tail->next = l2;
tail = l2;
l2 = l2->next;
}
}
if (l1)
{
tail->next = l1;
}
if (l2)
{
tail->next = l2;
}
return head;
}