Example 1 — One lap and five steps around a ring
Three nodes linked into a circle.
#include <stdio.h>
struct Node { int data; struct Node *next; };
int main(void) {
struct Node a = {1, NULL}, b = {2, NULL}, c = {3, NULL};
a.next = &b;
b.next = &c;
c.next = &a;
struct Node *p = &a;
printf("one lap:");
do {
printf(" %d", p->data);
p = p->next;
} while (p != &a);
printf("\nfive steps:");
p = &a;
for (int i = 0; i < 5; i++) {
printf(" %d", p->data);
p = p->next;
}
printf("\n");
return 0;
} How It Works
c.next = &acloses the circle.- The
do-whileruns once before testing, then stops when it returns toa. - Counting steps lets you wrap around forever without special cases.
