题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
}
};
递归实现:
参考斐波数列:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)// 递归的结束条件取决于最短的一个
return pHead2;
else if(pHead2==NULL)
return pHead1;
ListNode* newhead=NULL;
// 两个链表逐个结点进行比较
if(pHead1->val<pHead2->val)//若PHead1小 则保存到新的数newhead
{
newhead=pHead1;
newhead->next=Merge(pHead1->next,pHead2);
}
else//否则PHead2小 则保存到新的数newhead
{
newhead=pHead2;
newhead->next=Merge(pHead1,pHead2->next);
}
return newhead;
}
};
运行结果:
其它版本:通过的代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
//新建一个head头节点,用来存合并的链表输出。
ListNode* head=new ListNode(-1);
head->next=NULL;
ListNode* root=head;
while(pHead1!=NULL&&pHead2!=NULL){
if(pHead1->val<pHead2->val)
{
head->next=pHead1;//
// head=pHead1;//1)输出head指针向后移位 可改为head=head.next 这样代码运行的存储空间小
head=head->next;//2)
pHead1=pHead1->next;//输入指针向后移位
}
else
{
head->next=pHead2;
// head=pHead2;输出head指针向后移位 可改为head=head.next
head=head->next;
pHead2=pHead2->next;
}
}
//把未结束的链表连接到合并后的链表尾部
if(pHead1!=NULL)
{
head->next=pHead1;
}
if(pHead2!=NULL)
{
head->next=pHead2;
}
return root->next;
}
};
上述非递归版本如果使用1):
2)
参考:https://www.nowcoder.com/profile/144949/codeBookDetail?submissionId=15716602