PY:
代码思路:
-
创建一个哑节点 head 作为合并后链表的头部,并创建一个指针
head
指向哑节点。 -
使用循环,比较两个链表当前节点的值,选择较小的节点加入合并后的链表,并将对应的链表指针向后移动。
-
循环直到其中一个链表为空,此时将另一个链表的剩余部分直接加入到合并后链表的末尾。
-
返回哑节点的下一个节点,即为合并后链表的头部。
# 定义头节点
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list1, list2):
# 时间复杂度:n,空间复杂度:n
head = ListNode()
current = head
# 遍历两个链表
while list1 and list2:
if list1.val < list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
if list1:
current.next = list1
elif list2:
current.next = list2
return head.next
C++:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) {
return l2;
} else if (!l2) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};