Detect loop in a linked list

Given a linked list, check if the linked list has loop or not.

code:

def check_for_loops(self):
temp = self.head
while(temp.next):
if temp.next.visited == 'visited':
return True
else:
temp.next.visited = 'visited'
temp = temp.next
return False

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sairam Penjarla

Sairam Penjarla

Looking for my next opportunity to make change in a BIG way