Detect loops in a linked list
C, non-golfed

The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though).

struct node
{
  void *value;
  struct node *next;
};

int has_loops(struct node *p)
{
  struct node *p1 = p, *p2 = p-&gt;next;
  if (!p2) return 0;

  while (p1 != p2) {
    // p1 goes one step
    p1 = p1-&gt;next;
    if (!p1) return 0;

    // p2 goes two steps
    p2 = p2-&gt;next;
    if (!p2) return 0;
    p2 = p2-&gt;next;
    if (!p2) return 0;
  }

  return 1;
}