解题思路: 假设有两个有序单链表List1、List2
首先创建新的空链表,用于存放结果
如果两个有序单链表均为空,结果链表为空;
如果有一个有序单链表为空,则结果链表为另一个链表;
如果两个有序单链表均不为空,则根据以下方法进行合并
合并结束的条件:两个链表有一个为空
//合并两个有序链表,合并后依然有序
ListNode * MergeOrderedList(ListNode *list1, ListNode *list2)
{
ListNode *cur1=list1;//指向第一个链表
ListNode *cur2=list2;//指向第二个链表
ListNode *result = NULL;//结果链表
ListNode *tail = NULL;//结果链表中的最后一个结点,方便尾插
ListNode *next;
//结束条件:两个链表有一个为空
while (cur1 != NULL && cur2 != NULL)
{
if (cur1->data <= cur2->data)
{
if (result != NULL)
{
next = cur1->next;
tail->next = cur1;
cur1->next = NULL;
tail = cur1;
cur1 = next;
}
else
{
next = cur1->next;
result = cur1;
cur1->next=NULL;
tail = cur1;
cur1 = next;
}
}
else
{
if (result != NULL)
{
next = cur2->next;
tail->next = cur2;
cur2->next = NULL;
tail = cur2;
cur2 = next;
}
else
{
next = cur2->next;
result = cur2;
cur2->next = NULL;
tail = cur2;
cur2 = next;
}
}
}
//有一个链表为空
if (cur1 == NULL)
{
tail->next = cur2;
}
if (cur2 == NULL)
{
tail->next = cur1;
}
return result;
}