题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
代码实现
//递归
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* pMerge = NULL;
if (pHead1==NULL)
return pHead2;
if (pHead2==NULL)
return pHead1;
if(pHead1->val<=pHead2->val)
{
pMerge = pHead1;
pMerge->next = Merge(pHead1->next,pHead2);
}
else
{
pMerge = pHead2;
pMerge->next = Merge(pHead1,pHead2->next);
}
return pMerge;
}
};
//非递归(错解)
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode* all =nullptr;
ListNode* p = nullptr;
ListNode* q = nullptr;
if(pHead1 == nullptr || pHead2 == nullptr ){
if(pHead1 == nullptr && pHead2 == nullptr ){
return nullptr;
}
if(pHead1 == nullptr){
return nullptr;
}
if(pHead2 == nullptr){
return nullptr;
}
}
if(pHead1 -> val > pHead2 -> val){
all = pHead2;
}
while(pHead1->next != nullptr && pHead2->next != nullptr ){
if(pHead1->val >= pHead2->next-> val){
q = pHead2;
pHead2 = pHead2->next;
}
else{
p = pHead1;
pHead1 = pHead1->next;
p->next = pHead2->next;
pHead1->next = p;
pHead1 = pHead1->next;
}
}
while(pHead1 != nullptr){
if(pHead1->val <= pHead2->val){
p = pHead1;
pHead1 = pHead1->next;
p->next = q->next;
q->next = p;
q = q->next;
}
else{
pHead2->next = p;
break;
}
}
return all;
}
};
//非递归正解
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL) return pHead2;
if (pHead2 == NULL) return pHead1;
ListNode* head = NULL;
if (pHead1->val < pHead2->val) {
head = pHead1;
pHead1 = pHead1->next;
}
else {
head = pHead2;
pHead2 = pHead2->next;
}
ListNode* temp = head;
while (pHead1 && pHead2) {
if (pHead1->val < pHead2->val) {
temp->next = pHead1;
temp = temp->next;
pHead1 = pHead1->next;
}
else {
temp->next = pHead2;
temp = temp->next;
pHead2 = pHead2->next;
}
}
if (pHead1)
temp->next = pHead1;
if (pHead2)
temp->next = pHead2;
return head;
}
};