题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
有点类似于归并排序的里面的一个基本操作,设置一个新的节点res,两个指针,分别指向两个输入,比较两个对应的val的大小来决定谁放到res的next里面去,考虑好边界情况即可解题。
具体代码如下:
1.递归版本:
/*
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 == nullptr) return pHead2;
if (pHead2 == nullptr) return pHead1;
if (pHead1->val > pHead2->val)
{
pHead2->next = Merge(pHead2->next, pHead1);
return pHead2;
}
else
{
pHead1->next = Merge(pHead1->next, pHead2);
return pHead1;
}
}
};
2.非递归版本
/*
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 == nullptr) return pHead2;
if (pHead2 == nullptr) return pHead1;
ListNode *p1, *p2, *tmp, *res;
p1 = pHead1;
p2 = pHead2;
if (p1->val < p2->val)
{
res = p1;
p1 = p1->next;
tmp = res;
}
else
{
res = p2;
p2 = p2->next;
tmp = res;
}
while(p1 && p2)
{
if (p1->val < p2->val)
{
tmp->next = p1;
tmp = tmp->next;
p1 = p1->next;
}
else
{
tmp->next = p2;
tmp = tmp->next;
p2 = p2->next;
}
}
if (p2) tmp->next = p2;
if (p1) tmp->next = p1;
return res;
}
};