Search My Blog

Saturday, June 9, 2012

detecting a loop in a linked list

boolean hasLoop(Node head)
{
Node slow = head;
Node fast = head;

while(slow && fast && fast.next)
{
  slow = slow.next;
  fast = fast.next.next;

  if(slow == fast)
   return true;
}

return false;
}

No comments:

Post a Comment