题目:

思路:

  1. 用快慢指针判断是否有环,若有环的话,相遇节点记为ptr
  2. 头节点和ptr也会相遇 ,解释如下

设环外的长度是a,入环点到相遇节点的距离是b,环的总长是b+c

快指针的路程是慢指针的两倍,快指针走的路程是a+b+n(b+c),慢指针走的路程是a+b

a+b+n(b+c)=2(a+b) => a=(n-1)(b+c)+c=>head和ptr在入环点相遇

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow, fast = head, head
        has_cycle = False
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if slow == fast:
                has_cycle = True
                break #要加break退出循环
                
        if not has_cycle:
            return None
        ptr = head
        while ptr != slow:
            ptr = ptr.next
            slow = slow.next
        return ptr



        

注意:

while fast and fast.next:
            fast = fast.next.next #这里要先变换fast和slow,因为一开始都指向head
            slow = slow.next
            if slow == fast:
                has_cycle = True
                break

下面这个是错的:

while fast and fast.next:
            if slow == fast:
                has_cycle = True
                break
            else:
                fast = fast.next.next 
                slow = slow.next

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐