Implement a circular linked list.
#include <stdio.h>
#include <stdlib.h>
/* keep a pointer to the TAIL: tail->next is the head, so both ends are O(1) */
int cl_push_back(node_t **tail, int v)
{
node_t *n = malloc(sizeof *n);
if (!n) return -1;
n->val = v;
if (*tail == NULL) n->next = n; /* single node points to itself */
else { n->next = (*tail)->next; (*tail)->next = n; }
*tail = n;
return 0;
}
void cl_print(const node_t *tail)
{
if (!tail) return;
const node_t *p = tail->next; /* head */
do { printf("%d ", p->val); p = p->next; } while (p != tail->next);
printf("\n");
}
Points: there is no NULL at the end, so traversal stops when you return to the start (do ... while); keeping a tail pointer gives O(1) insertion at both ends. Uses: round-robin scheduling lists, circular buffers of objects.