题目描述
思路
利用哨兵头结点,用两个指针cur1,cur2指向list1,list2比较,val值小的,拿下来尾插到guard的后面,用一个指针tail用来记录尾。
注意:记得malloc一个哨兵头结点
分析情况:
1.当有一个链表为空,那么那那个不为空的链表直接尾插到guard后面就好。
2.如果,两个链表都为空,那么返回空。(把guard->next值初始化为空,最后返回,或者最后将tail->next置为空。
3.两个练表都不为空,比较大小,会有一个链表先走完,会有一个剩余,当一个先走完了就结束,后续在进行判断,把不为空的那个链表的剩余直接尾插到tail后面。
代码
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
struct ListNode* cur1=list1;
struct ListNode* cur2=list2;
struct ListNode* guard=(struct ListNode*)malloc(sizeof(struct ListNode));
guard->next=NULL;
struct ListNode* tail=guard;
//cur1,cur2有一个结束了,就是有一个指向空了,就退出循环
while(cur1&&cur2)
{
if(cur1->val < cur2->val)
{
//尾插到tail的后面
tail->next=cur1;
//更新cur1
cur1=cur1->next;
}
else
{
tail->next=cur2;
cur2=cur2->next;
}
tail=tail->next;//更新tail
}
//有一个可能会有剩余,直接尾插,因为本身就是升序
if(cur1!=NULL)
{
tail->next=cur1;
}
if(cur2!=NULL)
{
tail->next=cur2;
}
//返回guard的下一个,即新的头
return guard->next;
}