返回
LeetCode_21: 合并两个有序链表
闲谈
2024-01-07 07:17:45
算法简介
给定两个升序链表 head1
和 head2
,合并这两个链表并返回一个新的升序链表。新链表是通过拼接给定的两个链表的所有节点组成的。
算法实现
Python
def mergeTwoLists(head1, head2):
# 创建一个虚拟头结点,用于方便处理
dummy = ListNode(0)
# 将虚拟头结点指向head1
current = dummy
# 循环遍历head1和head2
while head1 and head2:
# 比较head1和head2的节点值,将较小的节点添加到当前节点后面
if head1.val < head2.val:
current.next = head1
head1 = head1.next
else:
current.next = head2
head2 = head2.next
# 移动当前节点到下一个节点
current = current.next
# 将剩余的链表连接到当前节点后面
if head1:
current.next = head1
if head2:
current.next = head2
# 返回虚拟头结点的下一个节点,即合并后的链表头结点
return dummy.next
Java
public ListNode mergeTwoLists(ListNode head1, ListNode head2) {
// 创建一个虚拟头结点,用于方便处理
ListNode dummy = new ListNode(0);
// 将虚拟头结点指向head1
ListNode current = dummy;
// 循环遍历head1和head2
while (head1 != null && head2 != null) {
// 比较head1和head2的节点值,将较小的节点添加到当前节点后面
if (head1.val < head2.val) {
current.next = head1;
head1 = head1.next;
} else {
current.next = head2;
head2 = head2.next;
}
// 移动当前节点到下一个节点
current = current.next;
}
// 将剩余的链表连接到当前节点后面
if (head1 != null) {
current.next = head1;
}
if (head2 != null) {
current.next = head2;
}
// 返回虚拟头结点的下一个节点,即合并后的链表头结点
return dummy.next;
}
C++
ListNode* mergeTwoLists(ListNode* head1, ListNode* head2) {
// 创建一个虚拟头结点,用于方便处理
ListNode* dummy = new ListNode(0);
// 将虚拟头结点指向head1
ListNode* current = dummy;
// 循环遍历head1和head2
while (head1 != nullptr && head2 != nullptr) {
// 比较head1和head2的节点值,将较小的节点添加到当前节点后面
if (head1->val < head2->val) {
current->next = head1;
head1 = head1->next;
} else {
current->next = head2;
head2 = head2->next;
}
// 移动当前节点到下一个节点
current = current->next;
}
// 将剩余的链表连接到当前节点后面
if (head1 != nullptr) {
current->next = head1;
}
if (head2 != nullptr) {
current->next = head2;
}
// 返回虚拟头结点的下一个节点,即合并后的链表头结点
return dummy->next;
}
复杂度分析
- 时间复杂度:
O(n+m)
,其中n
和m
分别是链表head1
和head2
的长度。在最坏的情况下,我们需要遍历这两个链表中的所有节点。 - 空间复杂度:
O(1)
,因为我们没有分配额外的空间来存储新的链表。
结语
LeetCode_21 是一道经典的链表合并题目,也是面试中经常被问到的题目。掌握了这道题目的解法,可以帮助您在面试中脱颖而出。希望本指南对您有所帮助,如果您还有其他问题,请随时提出。