外观
合并两个有序链表
⭐ 题目日期:
小米 - 2024/11/1
🌳 题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
🕵🏽 面试评估:
这道题考察链表的基础操作,属于简单题
🧗难度系数:
⭐️ ⭐️
📝思路分析:
合并两个有序链表,新链表的头节点不确定,所以我们可以创建一个哑节点 (DummyNode) 作为新链表的头节点,再依次遍历两个链表将较小的节点(比较 Cur 1 与 Cur 2 的大小)连接到新链表,重复以上操作直到所有节点都连接到新链表上,最后返回 DummyNode.next。
💻代码 :
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummyNode = new ListNode(0);
ListNode cur = dummyNode;
ListNode cur1 = list1;
ListNode cur2 = list2;
while (cur1 != null && cur2 != null) {
if (cur1.val <= cur2.val) {
cur.next = cur1;
cur1 = cur1.next;
} else {
cur.next = cur2;
cur2 = cur2.next;
}
cur = cur.next;
}
if (cur1 == null) {
cur.next = cur2;
} else {
cur.next = cur1;
}
return dummyNode.next;
}
}
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummyNode = ListNode(0)
cur = dummyNode
cur1 = list1
cur2 = list2
while cur1 is not None and cur2 is not None:
if cur1.val <= cur2.val:
cur.next = cur1
cur1 = cur1.next
else:
cur.next = cur2
cur2 = cur2.next
cur = cur.next
if cur1 is None:
cur.next = cur2
else:
cur.next = cur1
return dummyNode.next
C++
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode dummyNode(0);
ListNode* cur = &dummyNode;
ListNode* cur1 = list1;
ListNode* cur2 = list2;
while (cur1 != nullptr && cur2 != nullptr) {
if (cur1->val <= cur2->val) {
cur->next = cur1;
cur1 = cur1->next;
} else {
cur->next = cur2;
cur2 = cur2->next;
}
cur = cur->next;
}
if (cur1 == nullptr) {
cur->next = cur2;
} else {
cur->next = cur1;
}
return dummyNode.next;
}
};
🚵🏻复杂度分析:
时间复杂度:O(n + m), n, m 分别为两链表的长度
空间复杂度:O(1)