1

I have the following implementation that checks to see if a linked list has a cycle. If it does, it would return true, and false if it doesn't.

It seems like the code is correct, but it is returning false even if it does have a cycle. What am I missing? Thank you

import java.util.*;
class ListNode {
 int val;
 ListNode next;
 ListNode(int x) {
 val = x;
 next = null;
 }
 }
class LinkedListCycle {
 boolean hasCycle(ListNode head) {
 if(head == null) {
 return false;
 }
 ListNode walker = head;
 ListNode runner = head;
 while(runner.next!=null && runner.next.next!=null) {
 walker = walker.next;
 runner = runner.next.next;
 if(walker==runner) return true;
 }
 return false;
 }
 public static void main(String args[]) {
 LinkedListCycle llc = new LinkedListCycle();
 ListNode ln = new ListNode(1);
 ln.next = new ListNode(2);
 ln.next.next = new ListNode(3);
 ln.next.next.next = new ListNode(4);
 ln.next.next.next.next = new ListNode(2);
 ln.next.next.next.next.next = new ListNode(1);
 System.out.println(llc.hasCycle(ln));
 }
 }
asked Nov 20, 2016 at 13:45
1
  • you'd better post the case, when there exist cycle and it return false. Commented Nov 20, 2016 at 13:52

1 Answer 1

6

The algorithm is indeed correct: the walker advancing by one step and the runner advancing by 2 steps, will eventually will meet if the list has a cycle, or else reach the end of the list.

This cycle detection implementation doesn't detect cycle in terms of node values, but in terms of nodes. There is no cycle here in terms of nodes:

ListNode ln = new ListNode(1);
ln.next = new ListNode(2);
ln.next.next = new ListNode(3);
ln.next.next.next = new ListNode(4);
ln.next.next.next.next = new ListNode(2);
ln.next.next.next.next.next = new ListNode(1);

There would be, if written like this:

ListNode ln = new ListNode(1);
ln.next = new ListNode(2);
ln.next.next = new ListNode(3);
ln.next.next.next = new ListNode(4);
ln.next.next.next.next = ln.next;
answered Nov 20, 2016 at 13:50
2
  • Thank you so much for the clarification. So are the node values are necessary in fact? And how is it that the walker will eventually meet the runner? Commented Nov 20, 2016 at 14:12
  • The node values are data. The point of data structures is to contain some data, isn't it. In this exercise they may seem pointless, well that's just how exercises are. The walker and the runner meet, just like if you run in circles with a faster runner, he will eventually overtake you, again, and again, and again. Commented Nov 20, 2016 at 14:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.