NO.21合并俩个有序链表
#递归解法 class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: if not list1: return list2#递归的终止条件 if not list2: return list1 if list1.val<list2.val: list1.next = self.mergeTwoLists(list1.next,list2) #python中需要self.引用 return list1 else: list2.next = self.mergeTwoLists(list2.next,list1) return list2
#双指针解法 #采用第一种dummy作为链表头结点 class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode() #设置虚拟节点 cur = dummy #遍历节点和虚拟节点指向同一处 while list1 and list2:# 遍历条件list1,list2都不为空 if list1.val <= list2.val: cur.next = list1 cur = cur.next list1 = list1.next else: cur.next = list2 cur = cur.next list2 = list2.next if list1:#如果剩余list1不为空 cur.next = list1 if list2:#如果剩余list2不为空 cur.next = list2 return dummy.next
1 2 3 4 5 6 7 8 9 | 总结一下dummy节点 1 - > 2 - > 3 - > 4 - > 5 head在 1 的位置,有一个指针n也在头部 为解决问题,设置虚假节点dummy,指向一个假的节点,设为 0 (这个不重要,一般不会读取) dummy. next 指向 1 ,即转为 0 - > 1 - > 2 - > 3 - > 4 - > 5 ,因此最后 return dummy. next 是原链表 而加入dummy后,自己的指针n也不指向头部 1 ,而是指向 0 - dummy这个位置 遍历链表 - - - while (n = = null) dummy节点的作用:作为新链表的头结点 解决链表头部的极端情况 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)