mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-06-18 11:59:33 -04:00
Create detect_cycle_II.py
This commit is contained in:
parent
5eaeb66493
commit
654bb8c76f
1 changed files with 27 additions and 0 deletions
27
linked_lists/detect_cycle_II.py
Normal file
27
linked_lists/detect_cycle_II.py
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# author: bt3gl
|
||||||
|
|
||||||
|
|
||||||
|
class ListNode:
|
||||||
|
def __init__(self, x):
|
||||||
|
self.val = x
|
||||||
|
self.next = None
|
||||||
|
|
||||||
|
|
||||||
|
def detectCycle(self, head):
|
||||||
|
|
||||||
|
seen = set()
|
||||||
|
node = head
|
||||||
|
|
||||||
|
while node is not None:
|
||||||
|
|
||||||
|
if node in seen:
|
||||||
|
return node
|
||||||
|
|
||||||
|
else:
|
||||||
|
seen.add(node)
|
||||||
|
node = node.next
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue