一、题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
- 示例 1:
- 输入:l1 = [1,2,4], l2 = [1,3,4]
- 输出:[1,1,2,3,4,4]
- 示例 2:
- 输入:l1 = [], l2 = []
- 输出:[]
- 示例 3:
- 输入:l1 = [], l2 = [0]
- 输出:[0]
- 提示:
- 两个链表的节点数目范围是 [0, 50]
- − 100 ≤ N o d e . v a l ≤ 100 -100 \leq Node.val \leq 100 −100≤Node.val≤100
- l1 和 l2 均按 非递减顺序 排列
二、解决思路和代码
1. 解决思路
- 分析:借助一个头指针,使用头插法合并两个有序链表
2. 代码
from typing import Optional
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]:
resHead = pre = ListNode(val=-1)
p1, p2 = list1, list2
while p1 and p2:
if p1.val<=p2.val:
pre.next = p1
p1 = p1.next
pre = pre.next
else:
pre.next = p2
p2 = p2.next
pre = pre.next
if p1: pre.next = p1
if p2: pre.next = p2
return resHead.next
if __name__ == '__main__':
l1 = [1,2,4]
l2 = [1,3,4]
head1 = ListNode(val=0)
head2 = ListNode(val=0)
pre1, pre2 = head1, head2
for i in range(len(l1)):
node = ListNode(val=l1[i])
pre1.next = node
pre1 = node
for i in range(len(l2)):
node = ListNode(val=l2[i])
pre2.next = node
pre2 = node
head3 = Solution().mergeTwoLists(head1.next, head2.next)
while head3:
print(head3.val)
head3 = head3.next
```