Created
August 1, 2018 19:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.