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;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment