← All problems · Data Structures
Detect a Cycle in a Linked List
Return 1 if a singly linked list contains a loop, otherwise zero. Use constant extra memory.
Implement int has_cycle(struct node *head).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Advance one pointer twice as fast as the other.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
struct node { struct node *next; };
int has_cycle(struct node *head)
{
struct node *slow=head,*fast=head; while(fast && fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast)return 1;}return 0;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
struct node { struct node *next; };
int has_cycle(struct node *head)
{
struct node *slow=head,*fast=head; while(fast && fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast)return 1;}return 0;
}
The pointers meet inside a cycle; otherwise the fast pointer reaches the end.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
struct node b={NULL},a={&b};
CHECK(has_cycle(NULL)==0);
CHECK(has_cycle(&a)==0);
CHECK((b.next=&a,has_cycle(&a)==1));
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}