Article Directory
Method 1: Re-splicing two linked lists: time O(mn), space O(1)
answer:
- Create head node
- Splice the two linked lists in order of size after the head node
- At the end of the loop, splice the remaining section to the back
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
// 1.把一个链表插入另一个链表里
ListNode* head = new ListNode(0);
ListNode* cur = head;
while (l1 && l2)
{
if (l1->val < l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 == nullptr ? l2 : l1;
return head->next;
}
};
Method 2: Recursion (no head node is created): time O(mn), space O(m) m>n
answer:
- End condition: one of the two linked lists is empty
- Create a node that points to the current smaller value, and the next node of the node points to the next node of the recursion
- Return node
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
// 1.递归处理:不创建头结点
if (l1 == nullptr)
return l2;
else if (l2 == nullptr)
return l1;
ListNode* head = nullptr;
if (l1->val < l2->val)
{
head = l1;
head->next = mergeTwoLists(l1->next, l2);
}
else
{
head = l2;
head->next = mergeTwoLists(l1, l2->next);
}
return head;
}
};