Mental Model
We want to check if the list loops back to an earlier node instead of ending.
Analogy: Imagine walking down a path and checking if you ever step on the same stone twice, meaning the path loops.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
head -> 1 -> [slow->2] -> [fast->3] -> 4 -> 2 (loop)
head -> 1 -> 2 -> [slow->3] -> 4 -> [fast->2] (loop)
head -> 1 -> 2 -> 3 -> [slow->4] -> [fast->4] (loop)
head -> 1 -> 2 -> 3 -> 4 -> 2 (loop detected) -> true
#include <stdio.h> #include <stdlib.h> // Node structure typedef struct Node { int data; struct Node* next; } Node; // Function to create a new node Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; return newNode; } // Function to detect if linked list is circular int isCircular(Node* head) { if (head == NULL) return 0; // empty list is not circular Node* slow = head; Node* fast = head; while (fast != NULL && fast->next != NULL) { slow = slow->next; // move slow by 1 fast = fast->next->next; // move fast by 2 if (slow == fast) { return 1; // cycle detected } } return 0; // no cycle } // Driver code int main() { Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); head->next->next->next = createNode(4); // Creating a cycle: last node points back to node with value 2 head->next->next->next->next = head->next; if (isCircular(head)) { printf("true\n"); } else { printf("false\n"); } return 0; }
if (head == NULL) return 0; // empty list is not circularslow = slow->next; // move slow by 1fast = fast->next->next; // move fast by 2if (slow == fast) { return 1; }if (head == NULL) return 0; // empty list is not circular
if (slow == fast) { return 1; }
while (fast != NULL && fast->next != NULL)