data-structures · intermediate · ~25 min

Detect a cycle in a linked list

Floyd's tortoise-and-hare algorithm (two pointers, different speeds).

Challenge

Given the head of a singly-linked list with typedef struct node { int v; struct node *next; } node_t;, return 1 if it has a cycle, 0 otherwise. Implement int has_cycle(node_t *head).

Why this matters

Floyd's tortoise-and-hare is the canonical example of using rates to find structure: it's used to detect cycles in CPU instruction traces, in random number generators, and in serialization graphs.

Input format

A pointer to the head (may be NULL).

Output format

1 if cycle exists, 0 otherwise.

Constraints

O(1) auxiliary memory. No malloc. No mutating the list.

Starter code

typedef struct node { int v; struct node *next; } node_t;
int has_cycle(node_t *head) { /* TODO */ return 0; }

Common mistakes

Comparing slow != fast before stepping (causes false positive when head==head); not checking fast->next before stepping fast twice (NPE on linear lists); using a hash set when O(1) memory is required.

Edge cases to handle

NULL head. Single node, no cycle. Single node, self-loop. Two-node cycle.

Complexity

O(n) time, O(1) memory.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.