输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
方法一:
思路:用递归
/*
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;
if(pHead1->val<pHead2->val){
newHead=pHead1;
newHead->next=Merge(pHead1->next,pHead2);
}else{
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)
{
ListNode* head=new ListNode(-1);
head->next=NULL;
ListNode* root=head;
while(pHead1!=NULL&&pHead2!=NULL){
if(pHead1->val<pHead2->val)//当pHead1要小时
{
head->next=pHead1;//新链表的第一个数据为pHead1的元素
head=head->next;//新链表的头结点下移一位
pHead1=pHead1->next;//输入指针向后移位
}
else
{
head->next=pHead2;
head=head->next;
pHead2=pHead2->next;
}
}
//把未结束的链表连接到合并后的链表尾部
if(pHead1!=NULL)//当pHead2已经为空链表时,将pHead1剩下的链表元素的第一个地址给head->next
{
head->next=pHead1;
}
if(pHead2!=NULL)
{
head->next=pHead2;
}
return root->next;
}
};