题目描述:
![](https://i-blog.csdnimg.cn/blog_migrate/c504bad2bcafcfe3ad3c2ef51242bf9d.png)
示例:
![](https://i-blog.csdnimg.cn/blog_migrate/548a8dd3e01147406710a2f86f8bc1a5.png)
思路:
分别创建指向头和尾的指针phead和list,头指针phead定位头作为返回值,尾指针list定位尾。将两个链表中较小元素尾插到phead后面。
![](https://i-blog.csdnimg.cn/blog_migrate/d9285aec0a6f526420bbb115121479e9.png)
![](https://i-blog.csdnimg.cn/blog_migrate/1046ae0e6f874d24e9c440186793a9e9.png)
![](https://i-blog.csdnimg.cn/blog_migrate/77d052fec9ec081752ac37413cbfd7c9.png)
![](https://i-blog.csdnimg.cn/blog_migrate/43d930df7aad87f933f8f6a46af9d7fa.png)
![](https://i-blog.csdnimg.cn/blog_migrate/c772982330e6976ee5254e4869472637.png)
![](https://i-blog.csdnimg.cn/blog_migrate/b324560691d12c85dcc895c76d988325.png)
![](https://i-blog.csdnimg.cn/blog_migrate/7a2ce3c1b7590882250e6378e1c4db37.png)
用带哨兵卫的头指针,phead一定不为空,可以简化代码
代码实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode* phead=NULL,*list=NULL;
struct ListNode* cur1=list1;
struct ListNode* cur2=list2;
if(cur1==NULL)
return cur2;
if(cur2==NULL)
return cur1;
while(cur1&&cur2)//都不为空
{
if(cur2->val<cur1->val)
{
if(phead==NULL)
{
phead=list=cur2;
}
else
{
list->next=cur2;
list=list->next;
}
cur2=cur2->next;
}
else
{
if(phead==NULL)
{
phead=list=cur1;
}
else
{
list->next=cur1;
list=list->next;
}
cur1=cur1->next;
}
}
while(cur1!=NULL)
{
list->next=cur1;
list=list->next;
cur1=cur1->next;
}
while(cur2!=NULL)
{
list->next=cur2;
list=list->next;
cur2=cur2->next;
}
return phead;
}