问题描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解法一
定义一个新的链表,将两个链表中的结点进行比较然后插入到新链表中。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead2==NULL){
return pHead1;
}
if(pHead1==NULL){
return pHead2;
}
if(pHead1==NULL&&pHead2==NULL){
return NULL;
}
ListNode* mergeList=new ListNode(-1);
ListNode* cur=mergeList;
while(pHead1!= NULL && pHead2!= NULL){
if(pHead1->val < pHead2->val){
cur->next=pHead1;
pHead1=pHead1->next;
}
else{
cur->next=pHead2;
pHead2=pHead2->next;
}
cur=cur->next;
}
while(pHead1!=NULL){
cur->next=pHead1;
pHead1=pHead1->next;
cur=cur->next;
}
while(pHead2!=NULL){
cur->next=pHead2;
pHead2=pHead2->next;
cur=cur->next;
}
return mergeList->next;
}
};
解法二
使用递归
/*
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* p1=pHead1;
ListNode* p2=pHead2;
ListNode* newHead=NULL;
if(p1->val<p2->val){
newHead=p1;
newHead->next=Merge(p1->next,p2);
}
else{
newHead=p2;
newHead->next=Merge(p2->next,p1);
}
return newHead;
}
};