题目链接:https://leetcode.cn/problems/merge-two-sorted-lists/description/
📕题目要求:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
🧠解题思路
方案一:不带哨兵位的尾插
方案二:带哨兵位的尾插
🍭代码示例
方案一代码示例如下:
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
struct ListNode* head = NULL;
struct ListNode* cur = NULL;
if(list1==NULL)
{
return list2;
}
if(list2==NULL)
{
return list1;
}
while(list1!=NULL&&list2!=NULL)
{
if(list1->val<list2->val)
{
if(cur==NULL)
{
head = cur = list1;
}
else
{
cur->next = list1;
cur = cur->next;
}
list1 = list1->next;
}
else
{
if(cur == NULL)
{
head = cur = list2;
}
else
{
cur->next = list2;
cur = cur->next;
}
list2 = list2->next;
}
}
if(list1==NULL)
{
cur->next = list2;
}
if(list2==NULL)
{
cur->next = list1;
}
return head;
}
方案二代码示例如下:
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* cur = head;
if(list1==NULL)
{
return list2;
}
if(list2==NULL)
{
return list1;
}
while(list1&&list2)
{
if(list1->val<list2->val)
{
cur->next = list1;
cur = cur->next;
list1 = list1->next;
}
else
{
cur->next = list2;
cur = cur->next;
list2 = list2->next;
}
}
if(list1==NULL)
{
cur->next = list2;
}
if(list2==NULL)
{
cur->next = list1;
}
struct ListNode* del = head;
head = head->next;
free(del);
return head;
}
这就是我对本题的理解,如果大家有更优的解,欢迎交流,一起进步!