I’m looking over interview questions, and I came across “How do you find out if a linked-list has an end? (i.e. the list is not a cycle).” It gives a solution (traverse it one and two nodes at a time, and see if the pointers are ever equal).
Couldn’t we just keep the pointer that we start at and see if while traversing it, we ever hit that pointer again? Or will that not work?
No. See the below case. You will just traverse the loop without ever hitting the start node of the list
Another way to find if there is a loop:
If you reverse the list, and remember the inital node, you will know that there is a cycle if you get back to the first node. While efficient, this solution changes the list and not suited for multithreaded applications.