sword_for_offer/docs/剑指 Offer 25. 合并两个排序的链表.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, l1: ListNode, l2: ListNode) -> ListNode:
cur = dum = ListNode(0)
while l1 and 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 if l1 else l2
return dum.next
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dum = new ListNode(0), cur = dum;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
}
else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 != null ? l1 : l2;
return dum.next;
}
}
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dum = new ListNode(0);
ListNode* cur = dum;
while(l1 != nullptr && l2 != nullptr) {
if(l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
}
else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 != nullptr ? l1 : l2;
return dum->next;
}
};