Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
Linked List Cycle的扩展题,要找到cycle的起始点,还是跟Linked List Cycle那题一样,维护两个指针,fast指针以两倍slow指针的速度往前走 如果两个指针相遇,则有cycle 此时移动slow指针到head节点,这时俩指针离cycle的起点距离一样,两个指针以同样的速度往前走,就会在cycle的起点相遇~
这题的数学分析推导一直没耐心看 仅仅是记住了这种做法 找时间再好好看看
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if head is None or head.next is None: return None
slow, fast = head, head
while fast != None and fast.next != None:
fast, slow = fast.next.next, slow.next
if fast == slow:
break
if fast != slow:
return None
slow = head
while slow != fast:
slow, fast = slow.next, fast.next
return slow
本文介绍了一种高效的方法来确定链表中循环的开始节点。通过使用快慢指针技巧,在不额外使用空间的情况下解决此问题。当快慢指针首次相遇后,将其中一个指针移回头部,然后同时向前移动直到再次相遇即为循环起点。
1210

被折叠的 条评论
为什么被折叠?



