selected_coding_interview/docs/21. 合并两个有序链表.md
根据题目描述, 链表 $l_1$ , $l_2$ 是 递增 的,因此容易想到使用双指针 $l_1$ 和 $l_2$ 遍历两链表,根据 $l_1.val$ 和 $l_2.val$ 的大小关系确定节点添加顺序,两节点指针交替前进,直至遍历完毕。
引入伪头节点: 由于初始状态合并链表中无节点,因此循环第一轮时无法将节点添加到合并链表中。解决方案:初始化一个辅助节点 $dum$ 作为合并链表的伪头节点,将各节点添加至 $dum$ 之后。
{:width=400}
<,,,,,,,,,,,,,,,>
Python 三元表达式写法 A if x else B ,代表当 $x = True$ 时执行 $A$ ,否则执行 $B$ 。
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
cur = dum = ListNode(0)
while list1 and list2:
if list1.val < list2.val:
cur.next, list1 = list1, list1.next
else:
cur.next, list2 = list2, list2.next
cur = cur.next
cur.next = list1 if list1 else list2
return dum.next
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dum = new ListNode(0), cur = dum;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
cur.next = list1;
list1 = list1.next;
}
else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
cur.next = list1 != null ? list1 : list2;
return dum.next;
}
}
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* dum = new ListNode(0);
ListNode* cur = dum;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
cur->next = list1;
list1 = list1->next;
}
else {
cur->next = list2;
list2 = list2->next;
}
cur = cur->next;
}
cur->next = list1 != nullptr ? list1 : list2;
return dum->next;
}
};