-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhasCycle.py
33 lines (31 loc) · 880 Bytes
/
hasCycle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
time: O(n), worst O(n) + K
"""
class Solution:
def hasCycle(self, head: ListNode) -> bool:
try:
slow = head
fast = head.next
while slow != fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None or head.next is None:
return
slow = head
fast = head.next
while slow != fast:
if fast is None or fast.next is None:
return False
slow = slow.next
fast = fast.next.next
return True