Why exactly do we need a "Circular Linked List" (singly or doubly) data structure?

user366312 picture user366312 · Aug 28, 2010 · Viewed 40.7k times · Source

Why exactly do we need a "Circular Linked List" (singly or doubly) data structure?

What problem does it solve that is evident with simple Linked Lists (singly or doubly)?

Answer

Andrew Cone picture Andrew Cone · Aug 28, 2010

A simple example is keeping track of whose turn it is in a multi-player board game. Put all the players in a circular linked list. After a player takes his turn, advance to the next player in the list. This will cause the program to cycle indefinitely among the players.

To traverse a circular linked list, store a pointer to the first element you see. When you see that element again, you have traversed the entire list.

void traverse(CircularList *c) {
  if (is_empty(c)) {
    return;
  }
  CircularList start = c;
  do {
    operateOnNode(c);
    c = c->next;
  } while(c != start);
}