使用双指针,慢指针每次走一步,快指针走两步,如果快慢指针相遇,则有环。
若有环,设定速度相同的双指针,一个从头节点出发,一个从快慢指针相遇节点出发,相遇点就是环的入口
证明过程:https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.md
# 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
"""
fast = head
slow = head
while (fast != None) and (fast.next != None):
slow = slow.next
fast = fast.next.next
if slow == fast:
curq = slow
curp = head
while (curp != curq):
curp = curp.next
curq = curq.next
return curp
return None