Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is this a fair/clean way to detect a cycle in a LinkedList? Should work for both single and double LinkedLists'.

public bool IsCircular()
{
    if (Head != null && Head.Next != null)
    {
        var slow = Head;
        var fast = Head.Next;
        while (slow.Next != null && fast.Next != null && fast.Next.Next != null)
        {
            if (slow == fast)
            {
                return true;
            }
            slow = slow.Next;
            fast = fast.Next.Next;
        }
        return false;
    }
    else
    {
        return Head != null ? (Head == Head.Next) : false;
    }
}
share|improve this question
up vote 0 down vote accepted

It detects a cycle very nicely. However, I've got a few remarks:

Personally I would rename your heads to slowHead and fastHead. The expression slowHead == fastHead makes more sense then.

Your else block will always return false though. So you can get rid of that and replace it with return false. If you do that, the return false after the while loop can be removed as well.

share|improve this answer
    
Heh, actually yeah, I guess you're right. Good catch, thank you so much! This is fun going back through this stuff :) – Scott yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.