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

前端 未结 10 1059
無奈伤痛
無奈伤痛 2021-01-30 08:27

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 doubl

10条回答
  •  被撕碎了的回忆
    2021-01-30 09:19

    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);
    }
    

提交回复
热议问题