HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Detecting cycle in LinkedList

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cycledetectinglinkedlist

Problem

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;
    }
}

Solution

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.

Context

StackExchange Code Review Q#125876, answer score: 2

Revisions (0)

No revisions yet.