输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
法一:迭代
每一次循环中,取较小数值的结点,尾插到新链表后。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(nullptr == pHead1)
return pHead2;
if(nullptr == pHead2)
return pHead1;
ListNode* newtail = nullptr;
ListNode* newhead = nullptr;
while(pHead1 && pHead2)
{
ListNode* cur = nullptr;
if(pHead1->val < pHead2->val)
{
cur = pHead1;
pHead1 = pHead1->next;
}
else
{
cur = pHead2;
pHead2 = pHead2->next;
}
// 插入结点
if(newhead == nullptr)
{
newhead = cur;
newtail = cur;
cur->next = nullptr;
}
else
{
// 不是空链表
newtail->next = cur;
cur->next = nullptr;
newtail = cur;
}
}
if(pHead1)
{
// 1链表还存在
newtail->next = pHead1;
}
if(pHead2)
{
newtail->next = pHead2;
}
return newhead;
}
};
法二:递归
递归终止条件:链表为空。
每次摘下较小值的结点插入到新链表尾部时,问题规模缩小,但仍然是合并两个排序的链表。
/*
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* newhead = nullptr, *newtail = nullptr;
ListNode* cur = pHead1->val < pHead2->val ? pHead1 : pHead2;
if(cur == pHead1)
{
pHead1 = pHead1->next;
}
else if(cur == pHead2)
{
pHead2 = pHead2->next;
}
if(newhead == nullptr)
{
newhead = cur;
newtail = cur;
newtail->next = nullptr;
}
else
{
newtail->next = cur;
newtail = cur;
cur->next = nullptr;
}
newtail->next = Merge(pHead1, pHead2);
return newhead;
}
};