Skip to content

Instantly share code, notes, and snippets.

@sarb1208
Created August 1, 2018 19:09
Show Gist options
  • Save sarb1208/a7e2551ab42330ff9e5b6960be1d5b8b to your computer and use it in GitHub Desktop.
Save sarb1208/a7e2551ab42330ff9e5b6960be1d5b8b to your computer and use it in GitHub Desktop.
Following is C code snippet for detecting a cycle in a singly linked list
/*The structure of linked list is the following
struct node
{
int data;
node* next;
};*/
int detectloop(struct node *list){
// your code goes here
if(list==0)
return 0;
if(list->data==-1)
return 1;
list->data = -1;
return detectloop(list->next);
}
@sarb1208
Copy link
Author

sarb1208 commented Aug 1, 2018

This is simple method to detect cycle in the singly linked list . There is floyd's cycle detecting algorithm , but this is simpler and elegant.
The data in each node can also be restored back using one extra variable . Instead of -1 , any other number can be used which is not in the linked list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment