I'm stuck on the following leetcode problem.
Given a singly linked list determine if there exists a cycle. If so, return True. Otherwise, return False.
My reasoning: Allow for two pointers to go through the entire single linked list. One of the pointers move one node at a time while the other pointer will touch every other node. If there exists a cycle the pointers will eventually meet.
Here is my attempt (in python):
# Edge Case
if head == None:
return False
currA = head
currB = head
while currA and currB:
currA = currA.next
if currB.next:
currB = currB.next.next
if currA == None or currB == None:
return False
if currA == currB:
return True
return False
I submitted this code to leetcode and I was able to pass all the test cases except the really long one.
However, the following code works fine (written by someone else):
if not head or not head.next: return False
slow, fast = head, head.next
while slow != fast:
if not fast or not fast.next: return False
slow, fast = slow.next, fast.next.next
return True
To me, the main difference is the while statement's condition. However, I still don't see the error in my code.