-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind_cycle_in_LL.py
29 lines (25 loc) · 1 KB
/
Find_cycle_in_LL.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
'''temp=head # Just put temp data in a list and every time check if
l=[] # temp.next present in list then their must me a cycle
while(temp):
if temp not in l:
l.append(temp)
temp=temp.next
else:
return True
return False'''
if head==None or head.next==None: # Using slow and fast pointer
return False # if slow and fast pointer conside that cycle exits
slow=fast=head
while(fast.next and fast.next.next): # optimized soln
slow=slow.next
fast=fast.next.next
if(slow==fast):
return True
return False