1.合并链表p1,p2到p1上
void CombineList(ListNode** p1,ListNode* p2)
{
if (*p1 == NULL)
{
*p1 = p2;
return;
}
if (p2 == NULL)
{
return;
}
ListNode* cur1 = NULL;
ListNode* pre1 = NULL;
ListNode* cur2 = NULL;
ListNode* pre2 = NULL;
ListNode* now = NULL;
cur1 = *p1;
pre1 = cur1;
cur2 = p2;
if (cur2->data <= cur1->data)
{
pre2 = cur2->next;
cur2->next = cur1;
cur1 = cur2;
pre1 = cur1->next;
cur2 = pre2;
}
else
{
now = pre1;
pre1 = cur1->next;
}
while (pre1&&cur2)
{
if (cur2->data <= pre1->data)
{
pre2 = cur2->next;
cur2->next = pre1;
now->next = cur2;
now = now->next;
cur2 = pre2;
}
else
{
now = pre1;
pre1 = pre1->next;
}
}
if (pre1 == NULL)
{
pre1 = pre2;
}
}
2.合并两个链表,,生成第三个链表 非递归
ListNode* NewCombineList(ListNode* p1, ListNode* p2)
{
ListNode* pNewList = NULL;
ListNode* p3 = NULL;
if (p1 == NULL)
return p2;
if (p2 == NULL)
return p1;
if (p1->data < p2->data)
{
pNewList = p3 = p1;
p1 = p1->next;
}
else
{
pNewList = p3 = p2;
p2 = p2->next;
}
while (p1&&p2)
{
if (p1->data < p2->data)
{
p3->next = p1;
p1 = p1->next;
p3 = p3->next;
}
else
{
p3->next = p2;
p2 = p2->next;
p3 = p3->next;
}
}
if (p1 == NULL)
p3 = p2;
if (p2 == NULL)
p3 = p1;
return pNewList;
}
3.合并两个链表,,生成第三个链表 递归
ListNode* ReNewCombineList(ListNode* p1, ListNode* p2)
{
ListNode* pNewList = NULL;
if (p1 == NULL)
return p2;
if (p2 == NULL)
return p1;
if (p1->data < p2->data)
{
pNewList = p1;
pNewList->next = ReNewCombineList(p1->next, p2);
}
else
{
pNewList = p2;
pNewList->next = ReNewCombineList(p1, p2->next);
}
return pNewList;
}