Linked List Cycle
@lycoding I had the same idea except that I used Java. But I got TLE error. Any idea why?
@sadia8288 There's a while slow is not fast. Since slow is designed to be slower than fast, if there's a cycle, fast will eventually catch up slow. Then return True.
I came up with a similar solution but simplified a bit more:
There's no need to check for
This information is contained in while(fast && fast->next)
I think O(0) space is meaningless in real world. it is good but not necessary. O(1) is efficient enough.
I'm wondering whether we could change the original list structure.
No one has replied
it still works, for you example: 1->2->3->4->2:
iteration, head, fast
If there is a cycle, fast will catch slow after some loops.
@wyddfrank it's truely not good enough to have modified the original list, and it seems impossible to reverse ite back when it has a loop.
You really don't need the initial test for
I it is handled in the while loop body. Here is my accepted code.
Therefore, we can see that
is always a solution. So the algorithm @JayWong gave can always detect if the linked list forms a cycle or not.
thank you for your analysis, i have no confusion now:-D
anytime my friend :)
Agreed. Didn't see any NPE. Correct me if I am wrong. :D
Disabled Categories are greyed out
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.