[英]Splitting Linked Lists Python
我最近开始学习数据结构,我想知道最后 3 行发生了什么......
def frontBackSplit(self):
source = self.root
# if the length is less than 2, handle it separately
if source is None or source.next is None:
return source, None
slow, fast = source, source.next
# advance `fast` two nodes, and advance `slow` one node
while fast:
fast = fast.next
if fast:
slow = slow.next
fast = fast.next
# `slow` is before the midpoint of the list, so split it in two
# at that point.
ret = source, slow.next
slow.next = None
return ret
我知道这个慢/快策略是找到中点,但是当:
ret = source, slow.next
slow.next = None
return ret
我不明白这如何允许拆分链接列表。 谁能帮助我吗?
当你这样做时:
ret = source, slow.next
这将创建一个包含两项的元组:当前列表的开头和第二个列表的开头。 然后你做:
slow.next = None
通过使第一个列表的末尾slow
来打破链条。 因此,当您返回ret
时,您将返回第一个列表的开头(现在以slow
结尾)和第二个列表的开头(从slow
之后的节点开始)。
说我们有
1 -> 2 -> 3 -> 4 -> 5
其中source
是 1, slow
是 3。当我们执行第一条语句时, ret
将指向 ( 1
, 4
)。 然后我们打破 3 的列表,我们剩下
( 1 -> 2 -> 3 , 4 -> 5 )
在 function 的开头, source
设置为头节点self.root
:
source
/---\ /---\ /---\ /---\ /---\ /---\
| | -> | | -> | | -> | | -> | | -> | |
\---/ \---/ \---/ \---/ \---/ \---/
迭代fast
移动指针并slow
列表。 当fast
从列表末尾掉下来时, slow
处于中间位置。 source
还在原来的地方。
source slow
/---\ /---\ /---\ /---\ /---\ /---\
| | -> | | -> | | -> | | -> | | -> | |
\---/ \---/ \---/ \---/ \---/ \---/
现在我们做:
ret = source, slow.next
请注意source
仍然指向列表的头部,但是我们在这一点之后不再使用它,所以它是无关紧要的; 让我们只关注ret
和slow
:
ret[0] slow ret[1]
/---\ /---\ /---\ /---\ /---\ /---\
| | -> | | -> | | -> | | -> | | -> | |
\---/ \---/ \---/ \---/ \---/ \---/
请注意, ret[0]
和ret[1]
位于我们要返回的两个半列表的头节点,但两者仍然是单个列表的一部分。 要真正拆分列表,我们需要切断slow
和ret[1]
之间的连接,即slow.next
指针:
slow.next = None
给我们:
ret[0] ret[1]
/---\ /---\ /---\ /---\ /---\ /---\
| | -> | | -> | | | | -> | | -> | |
\---/ \---/ \---/ \---/ \---/ \---/
现在我们有两个列表,我们将它们作为ret
返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.