142.环形链表2
142. 环形链表2
题意
在存在环的情况下,找出环的起点位置;
解题思路
先找到环中相遇的地方,然后让其中一方从起始位置移动,一方从相遇位置移动,双方相遇的时候就是环的起点;
证明图如下:
证明可参考这里
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
slow, fast = head, head
iscycle = False
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
iscycle = True
break
if iscycle:
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
else:
return None
简化代码
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast is slow:
slow = head
while fast is not slow:
fast, slow = fast.next, slow.next
return slow
return None

关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法