题目描述:
方法一:O(n) O(n)
# 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 """ visited = set() node = head while node: if node in visited: #return visited.index(head.val) return node else: visited.add(node) node = node.next return None
方法二:快慢指针 O(N) O(1)
class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ fast, slow = head, head while True: if not (fast and fast.next): return fast, slow = fast.next.next, slow.next if fast == slow: break fast = head while fast != slow: fast, slow = fast.next, slow.next return fast
原文:https://www.cnblogs.com/oldby/p/11199575.html