题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
方案一:迭代(C++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (nullptr == l1) {
return l2;
} else if (nullptr == l2) {
return l1;
}
ListNode* h1 = l1;
ListNode* h2 = l2;
ListNode* head = nullptr;
ListNode* cur = nullptr;
while (h1 || h2) {
if ((h2 == nullptr) || (h1 != nullptr && h1->val < h2->val)) {
if (nullptr == cur) {
cur = head = h1;
} else {
cur->next = h1;
cur = cur->next;
}
h1 = h1->next;
} else {
if (nullptr == cur) {
cur = head = h2;
} else {
cur->next = h2;
cur = cur->next;
}
h2 = h2->next;
}
}
return head;
}
};
时间复杂度
空间复杂度
方案二:递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (nullptr == l1) {
return l2;
} else if (nullptr == l2) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l2->next, l1);
return l2;
}
}
};
时间复杂度
空间复杂度
注:
递归调用 mergeTwoLists 函数时需要消耗栈空间,栈空间的大小取决于递归调用的深度。结束递归调用时 mergeTwoLists 函数最多调用 n+mn+m 次,因此空间复杂度为 O(n+m)O(n+m)