题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题目分析
merge函数的写法,递归与非递归两种。核心思想都是用两个指针,用不断移动两个指针,小的放在前面。下面两种比较好的写法。
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == nullptr)
return pHead2;
if (pHead2 == nullptr)
return pHead1;
return pHead1->val > pHead2->val ?
(pHead2->next = Merge(pHead1, pHead2->next), pHead2) :
(pHead1->next = Merge(pHead1->next, pHead2), pHead1);
}
};
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* node=NULL;
if(pHead1==NULL){return node=pHead2;}
if(pHead2==NULL){return node=pHead1;}
if(pHead1->val>pHead2->val){
node=pHead2;
node->next=Merge(pHead1,pHead2->next);
}else
{
node=pHead1;
node->next=Merge(pHead1->next,pHead2);
}
return node;
}
};
非递归版本
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1 && !pHead2)return NULL;
if (!pHead1)return pHead2;
if (!pHead2)return pHead1;
ListNode *p = new ListNode(0);
ListNode *head = p;
while (pHead1 && pHead2)
{
if (pHead1->val < pHead2->val)
{
head->next = pHead1;
pHead1 = pHead1->next;
}
else
{
head->next = pHead2;
pHead2 = pHead2->next;
}
head = head->next;
}
if (pHead1)
head->next = pHead1;
if (pHead2)
head->next = pHead2;
return p->next;
}
};
这里还有一个思考比如两个序列{2,3,5,6,7,8} 和{0,1,4,9,10,11}可以考虑一次把一段加入合并的链表中。
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)
{
return pHead2;
}
if(pHead2==NULL){
return pHead1;
}
ListNode* i=pHead1,* j=pHead2;
ListNode* iPre,*jPre;
while(i!=NULL&&j!=NULL){
while(i!=NULL&&j!=NULL&&i->val<=j->val){
iPre=i;
i=i->next;
}
if(j){
iPre->next=j;
}
while(i!=NULL&&j!=NULL&&i->val>j->val){
jPre=j;
j=j->next;
}
if(i){
jPre->next=i;
}
}
return pHead1->val<=pHead2->val?pHead1:pHead2;
}
};