方法1:依次比较,取最小的尾插
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
if (list1 == NULL)
return list2;
if (list2 == NULL)
return list1;
struct ListNode* cur1 = list1, * cur2 = list2;
struct ListNode* head = NULL, * tail = NULL;
while (cur1 && cur2)
{
//list1->val < list2->val
if (cur1->val < cur2->val)
{
if (head == NULL)
{
head = tail = cur1;
}
else
{
tail->next = cur1;
tail = tail->next;
}
cur1 = cur1->next;
}
else //list1->val >= list2->val
{
if (head == NULL)
{
head = tail = cur2;
}
else
{
tail->next = cur2;
tail = tail->next;
}
cur2 = cur2->next;
}
}
if (cur1)//cur2已经尾插完,只剩下了cur1
{
tail->next = cur1;
}
if (cur2)//cur1已经尾插完,只剩下了cur2
{
tail->next = cur2;
}
}
方法二.使用哨兵节点来解决。
优点:不需要判断头节点为空的情况。
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
struct ListNode* cur1 = list1, * cur2 = list2;
struct ListNode* guard = NULL, * tail = NULL;
guard = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next = NULL;
while (cur1 && cur2)
{
if (cur1->val < cur2->val)
{
tail->next = cur1;
tail= tail->next;
cur1 = cur1->next;
}
else
{
tail->next = cur2;
tail = tail->next;
cur2 = cur2->next;
}
}
if (cur1)
{
tail->next = cur1;
}
if (cur2)
{
tail->next = cur2;
}
struct ListNode* head = guard->next;
free(guard);
return head;
}