Skip to content

Commit dd0109c

Browse files
committed
linked list cycle
1 parent c138a61 commit dd0109c

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

linkedlist/hascycle.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Node():
2+
def __init__(self, val: int, next: "Node" = None):
3+
self.val = val
4+
self.next = next
5+
def __str__(self) -> str:
6+
return str(self.val)
7+
8+
def hasCycle(n: Node) -> bool:
9+
slow = fast = n
10+
while fast and fast.next:
11+
slow = slow.next
12+
fast = fast.next.next
13+
if slow == fast:
14+
break
15+
16+
if slow != fast: return None
17+
18+
start = n
19+
while start != slow:
20+
start = start.next
21+
slow = slow.next
22+
return slow
23+
24+
def printHasCycle(head: Node):
25+
r1 = hasCycle(head)
26+
print(f'cycle? {"starting in " + str(r1.val) if r1 else False}') #None
27+
28+
last = Node(5)
29+
head = Node(1, Node(2, Node(3, Node(4, last))))
30+
printHasCycle(head) # False
31+
last.next = head
32+
printHasCycle(head) # Starting in 1
33+
34+

0 commit comments

Comments
 (0)