I’m currently relearning some of my old previous knowledge in data structures, and decided to work on problems such as HackerRank. I came across an easy question where we have to detect a cycle in a linked list, but I can’t seem to understand what I’m doing wrong. I have looked at other answers, and understood their syntax and logic, but can’t seem to find the logic in which my code fails.

boolean hasCycle(Node head) { if (head == null || head.next == null){ return false; } Node first = head; Node second = head.next; while (second != null){ if (first == second) { return true; } first = first.next; second = second.next.next; } return false; }

As I understand it your list can have a circle in any of the nodes, not just the first. Your code is far from the solution.

You can simplify how you think of the problem as having to check if a node is visited more than once.

To do this you can use a helper function like this

boolean visitedMoreThanOnce(Node head) { if (head.next == null){ return false; } Node second = head.next; while (second != null){ if (head == second) { return true; } second = second.next; } return false; }

Then your function could be

boolean hasCycle(Node head) { Node first = head; while (first != null){ if (visitedMoreThanOnce(first)) { return true; } first = first.next; } return false; }

Note that I solved it with your function signature. By looking at the problem in the link provided in the comments in your question, it seams that head should be a pointer. In that case you will need to use -> operator, instead of .