while (head != null) { if (nodeSet.contains(head)) return head; nodeSet.add(head); head = head.next; }
returnnull; } }
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classListNode: def__init__(self, x): self.val = x self.next = None classCycleList: defhasCycle(self, head): node_set = set() while head: if head in node_set: return head node_set.add(head) head = head.next returnNone
classListNode: def__init__(self, x): self.val = x self.next = None
classCycleList: defhasCycle(self, head): if head and head.nextand head.next.next: slow = head.next fast = head.next.next while slow != fast: if fast.nextand fast.next.next: slow = slow.next fast = fast.next.next else: returnNone fast = head while slow != fast: slow = slow.next fast = fast.next return fast else: returnNone
classListNode: def__init__(self, x): self.val = x self.next = None
classCycleList: defhasCycle(self, head): if head and head.nextand head.next.next: slow = head.next fast = head.next.next while slow != fast: if fast.nextand fast.next.next: slow = slow.next fast = fast.next.next else: returnFalse returnTrue else: returnFalse