Skip to content

Latest commit

 

History

History
29 lines (25 loc) · 730 Bytes

87. 环形链表 II.md

File metadata and controls

29 lines (25 loc) · 730 Bytes

给定一个链表,返回链表开始入环的第一个节点。如果链表无环,则返回 null。

# 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:
        slow = fast = head
        flag = False
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                flag = True
                break
        if not flag:
            return None

        fast = head
        while fast != slow:
            fast = fast.next
            slow = slow.next
        
        return fast