DATA STRUCTURES PROGRAM • SINGLY LINKED LISTS

Detect a Linked-List Cycle with Floyd's Algorithm

Learn how to detect a linked-list cycle with floyd's algorithm using a clear C program.

AdvancedLinked listNodePointers

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Cycle detected.

COMPLETE C PROGRAM

Complete C implementation

dsa-detect-linked-list-cycle.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node { int data; struct Node *next; };

struct Node *create_node(int value)
{
    struct Node *node = malloc(sizeof *node);
    if (node == NULL) { perror("malloc"); exit(EXIT_FAILURE); }
    node->data = value;
    node->next = NULL;
    return node;
}

void append(struct Node **head, int value)
{
    struct Node *node = create_node(value);
    if (*head == NULL) { *head = node; return; }
    struct Node *current = *head;
    while (current->next != NULL) current = current->next;
    current->next = node;
}

void print_list(const struct Node *head)
{
    while (head != NULL) { printf("%d ", head->data); head = head->next; }
    putchar('\n');
}

void free_list(struct Node *head)
{
    while (head != NULL) { struct Node *next = head->next; free(head); head = next; }
}

int main(void)
{
    struct Node *head = NULL;
    append(&head, 10); append(&head, 20); append(&head, 30); append(&head, 40);
    struct Node *tail = head;
    while (tail->next != NULL) tail = tail->next;
    tail->next = head->next;
    const struct Node *slow = head, *fast = head;
    int cycle = 0;
    while (fast != NULL && fast->next != NULL) {
        slow = slow->next; fast = fast->next->next;
        if (slow == fast) { cycle = 1; break; }
    }
    puts(cycle ? "Cycle detected." : "No cycle.");
    tail->next = NULL;
    free_list(head);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Cycle detected.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. A one-step pointer and a two-step pointer must meet when a cycle exists.
  3. Display the computed result.

A one-step pointer and a two-step pointer must meet when a cycle exists.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.