题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题目链接:牛客网
模拟归并排序的合并的过程~
可以用迭代,也可以用递归,递归的写法十分整洁易读!!!
// 递归版本
/*
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;
if (pHead2 == NULL)
return pHead1;
ListNode* head;
if (pHead1->val <= pHead2->val) {
head = pHead1;
head->next = Merge(pHead1->next, pHead2);
} else {
head = pHead2;
head->next = Merge(pHead1, pHead2->next);
}
return head;
}
};
// 迭代版本
/*
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;
if (pHead2 == NULL)
return pHead1;
// 找出第一个节点
ListNode* now = NULL;
if (pHead1->val <= pHead2->val) {
now = pHead1;
pHead1 = pHead1->next;
} else {
now = pHead2;
pHead2 = pHead2->next;
}
ListNode* head = now;
// 模仿归并排序的合并操作
while (pHead1 != NULL || pHead2 != NULL) {
if (pHead1 == NULL) {
MergeHelper(now, pHead2);
continue;
}
if (pHead2 == NULL) {
MergeHelper(now, pHead1);
continue;
}
if (pHead1->val <= pHead2->val)
MergeHelper(now, pHead1);
else
MergeHelper(now, pHead2);
}
return head;
}
void MergeHelper(ListNode*& master, ListNode*& guest) {
master->next = guest;
master = master->next;
guest = guest->next;
}
};