python - 如果我通过 slow.next 而不是 mid 为什么合并排序不起作用?
问题描述
在合并排序的这段代码中,为什么可以在对 sortList 的递归调用中直接传递 mid 而不能传递 slow.next?在第 13 行中,传递 mid = slow.next 与直接传递 slow.next 有何不同?
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
fast = head.next
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
mid = slow.next
slow.next = None
l = self.sortList(head)
r = self.sortList(slow.next)##instead pass mid here, and it works.
return self.merge(l,r)
def merge(self, l, r):
if not l or not r:
return l or r
if l.val > r.val:
l, r = r, l
# get the return node "head"
head = pre = l
l = l.next
while l and r:
if l.val < r.val:
l = l.next
else:
nxt = pre.next
pre.next = r
tmp = r.next
r.next = nxt
r = tmp
pre = pre.next
# l and r at least one is None
pre.next = l or r
return head
解决方案
您首先分配slow.next
给mid
,所以mid
现在保存列表第二部分的开始。然后你分配None
到slow.next
,所以如果你现在调用self.sortList(slow.next)
,列表的第二部分将不会被排序。
如果您调用self.sortList(mid)
,那么因为mid
是指向列表第二部分的指针,所以合并排序有效。
推荐阅读
- java - 通过忽略“$”或任何字符来解析 Groovy 字符串(ps:无法控制输入数据)
- javascript - 如何获取距离 X 日期的天数并在 X 日期达到 0 时停止计数
- android - Android:当用户尝试在设置页面上启用 chrome 并按下后退按钮时,应用程序会重新启动
- javascript - RegEx 用于验证三个字母数字条件
- kubernetes - 删除 pod 但将作业标记为成功
- swift - 使用 3rd-party 库编译 swift 框架
- html - CSS 正文作者样式不适用,无法覆盖用户代理样式表
- java - 从 Java 中读取 nodejs 的标准输出(使用 apache commons exec)。线程安全与否?
- c# - 如何从 SFTP 读取 CSV 文件并使用 CSVHelper 解析内容而不在本地保存 CSV
- laravel - 如何从两者之间有很多分离度的模型中获得 Eloquent 模型集合?