题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路1:非递归——创建两个指针,一个用于记录链表头节点,用于return,一个人用于链表遍历
/*struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
//思路1:非递归
if (!pHead1 && !pHead2) //相当于if (pHead1==nullptr && pHead2==nullptr)
return nullptr;
if (!pHead1)
return pHead2;
if (!pHead2)
return pHead1;
ListNode* head = nullptr;;
ListNode* node = head;
while (pHead1 && pHead2)
{
if (pHead1->val <= pHead2->val) {
if (!head)
head = node = pHead1;
else
{
node->next = pHead1;
node = node->next;
}
pHead1 = pHead1->next;
}
else
{
if (!head)
head = node = pHead2;
else
{
node->next = pHead2;
node = node->next;
}
pHead2 = pHead2->next;
}
}
if (!pHead1)
node->next = pHead2;
if (!pHead2)
node->next = pHead1;
return head;
}
};
思路2:递归
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1 && !pHead2)
return nullptr;
if (!pHead1)
return pHead2;
if (!pHead2)
return pHead1;
ListNode* head = nullptr; //每次递归时指向头节点
if (pHead1->val <= pHead2->val) {
head = pHead1;
head->next = Merge(pHead1->next, pHead2);
}
else
{
head = pHead2;
head->next = Merge(pHead1, pHead2->next);
}
return head;
}
};