题目链接
迭代法
思路:设置一个哨兵节点(head节点),方便处理首元节点。用两个指针分别指向头部,用head指向val较小的那个节点,较小的节点并往后移。直到某个链表遍历完成,将另一个链表剩余部分直接连接即可。
代码
/**
* 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) {
ListNode* head = new ListNode(0); //设置哨兵节点
ListNode* cur = head;
while (l1 && l2){ //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 ? l1 : l2; //将剩余的移到cur链表上
return head -> next;
}
};
时间复杂度O(n):最坏遍历2n个节点
空间复杂度O(1):几个常量指针
递归法
代码
/**
* 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 (l1 == nullptr) { //终止条件,某个链表为空,返回另一个链表
return l2;
}
if (l2 == nullptr) {
return l1;
}
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2); //递归,拼接下一个节点
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
时间复杂度O(n):同样最坏遍历2n个节点
空间复杂度O(n):栈的最大深度为2n