SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Linked List Implementation(detect a loop in a linked list)
Linked List Implementation(detect a loop in a linked list)
#include
#include
struct node { int data; struct node *next; }; struct node* newnode(int data) { struct node *new=(struct node*)malloc(sizeof(struct node)); new->data=data; new->next=NULL; return new; } void insertastail(struct node **head,int data) { struct node *temp; struct node *current=*head; if(current==NULL) { *head=newnode(data); } else { temp=newnode(data); while(current->next!=NULL) current=current->next; current->next=temp; } } void printlist(struct node *head) { struct node *current=head; while(current!=NULL) { printf("%d ",current->data); current=current->next; } } int detectloop(struct node *head) { struct node *slow=head; struct node *fast=head; while(fast!=NULL && fast->next!=NULL) { slow=slow->next; fast=fast->next->next; if(slow==fast) return 1; } return 0; } int main(void) { struct node *head=NULL; struct node *current; int data,size; int i,n; scanf("%d",&size); for(i=0;i
next!=NULL) { current=current->next; } current->next=head->next->next;*/ if(detectloop(head)) printf("loop detected"); else printf("loop not detected"); return 0; }
PREVIOUS
NEXT
HOME