题解 | #合并两个排序的链表#
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
尾插法
//尾插法
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 )
{
if(pHead1==NULL)
{
return pHead2;
}
if(pHead2==NULL)
{
return pHead1;
}
struct ListNode* Head=NULL;
struct ListNode* Tail=NULL;
while(pHead1!=NULL&&pHead2!=NULL)
{
if((pHead1->val)<(pHead2->val))
{
if(Head==NULL)
{
Head=pHead1;
//找小的为首结点
Tail=Head;
}
else
{
Tail->next=pHead1;
Tail=Tail->next;
}
pHead1=pHead1->next;
}
else
{
if(Head==NULL)
{
Head=pHead2;
//找小的为首结点
Tail=Head;
}
else
{
Tail->next=pHead2;
Tail=Tail->next;
}
pHead2=pHead2->next;
}
}
if(pHead2==NULL)
{
Tail->next=pHead1;
Tail=Tail->next;
}
if(pHead1==NULL)
{
Tail->next=pHead2;
Tail=Tail->next;
}
return Head;
}