Technical Interview

Tips, questions, answers and puzzles at
www.technical-interview.com

Thursday, April 22, 2010

Write a function which will test whether or not there is a cycle in a single linked list

Q:

Write a function which will test whether or not there is a cycle in a single linked list

A:

public bool hasLoop(Node head)
{
Node first = head;
Node second = head;
while (first && second &&
first.Next && second.Next &&
second.Next.Next)
{
first = first.Next;
second = second.Next.Next;
if (first == second)
{
// Found loop
return true;
}
}
return false;
}

No comments:

Post a Comment