#142. 环形链表 II

题目:

思路:利用两个指针对链表进行遍历,如果两指针指向同一个节点时,令fast=head,然后重新进行遍历,再次相遇时的节点即为环的起点。

代码:

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

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        fast, slow = head, head
        while True:
            if  (fast==None or fast.next==None): return
            fast, slow = fast.next.next, slow.next
            if fast == slow: break#相遇即要跳出
        fast = head
        while fast!=slow :#从头开始走
            fast = fast.next
            slow = slow.next
        return slow
原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/14791122.html