描述:
示例:
代码:
方法一:
正常比较两个链表的头节点,然后插入新链表的尾部
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (nullptr == pHead1) return pHead2;
if (nullptr == pHead2) return pHead1;
ListNode* new_head = nullptr;
ListNode* new_tail = nullptr;
while (pHead1 && pHead2) {
ListNode* p = pHead1->val < pHead2->val ? pHead1 : pHead2;
if (p == pHead1) pHead1 = pHead1->next;
else pHead2 = pHead2->next;
if (nullptr == new_head) {
new_head = p;
new_tail = p;
}
else {
new_tail->next = p;
new_tail = p;
}
}
if (nullptr == pHead1) new_tail->next = pHead2;
else if (nullptr == pHead2) new_tail->next = pHead1;
return new_head;
}
};
方法二:递归
比较两个链表的头结点,然后删除头部插入新链表的尾部,然后再传入函数中,,,
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (nullptr == pHead1) return pHead2;
if (nullptr == pHead2) return pHead1;
ListNode* new_head = nullptr;
if (pHead1->val < pHead2->val) {
new_head = pHead1;
pHead1 = pHead1->next;
}
else {
new_head = pHead2;
pHead2 = pHead2->next;
}
new_head->next = Merge(pHead1, pHead2);
return new_head;
}
};