We can detect loop using both recursive and iterative way but here, we will look for only iterative solution.
Iterative solution in Python -
def detectLoop(head): |
a=set() | |
temp=head | |
while temp: | |
if temp in a: | |
return True | |
else: | |
a.add(temp) | |
temp=temp.next | |
return False |
We created a set to store data of linkedlist, if next of any node points again to node already in a set, the loop is detected. If whole linkedlist is traversed and null is reached, no loop in the linkedlist and we return False at the end.
Comments
Post a Comment