• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

4小时前 1次浏览

# 代码实现：

``````/**
* 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*n1,*n2;
n1 = l1;
n2 = l2;
while(n1 && n2)
{
if(n1->val<n2->val)
{
if(tail == NULL)
{
}
else
{
tail->next = n1;
tail = n1;
}
n1 = n1->next;
}
else
{
if(tail == NULL)
{
}
else
{
tail->next = n2;
tail = n2;
}
n2 = n2->next;
}
}
if(n1)
{
tail->next = n1;
}
if(n2)
{
tail->next = n2;
}

}
``````

# 优化方案：

``````struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
struct ListNode*n1,*n2;
n1 = l1;
n2 = l2;
//先取一个小的做头节点
if(n1->val < n2->val)
{
n1 = n1->next;
}
else
{
n2 = n2->next;
}
while(n1 && n2)
{
if(n1->val<n2->val)
{
tail->next = n1;
tail = n1;
n1 = n1->next;
}
else
{
tail->next = n2;
tail = n2;
n2 = n2->next;
}
}
if(n1)
{
tail->next = n1;
}
if(n2)
{
tail->next = n2;
}

}
``````
``````struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
struct ListNode*n1,*n2;
n1 = l1;
n2 = l2;
//给一个哨兵位的头节点，方便尾插，处理完以后，再删掉。
newhead = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
while(n1 && n2)
{
if(n1->val<n2->val)
{
tail->next = n1;
tail = n1;
n1 = n1->next;
}
else
{
tail->next = n2;
tail = n2;
n2 = n2->next;
}
}
if(n1)
{
tail->next = n1;
}
if(n2)
{
tail->next = n2;
}