Search This Blog

Sunday, September 21, 2014

WAP to detect loop in a singly linked list

1:  void loop_detection()  
2:  {  
3:    list_t *slow = start;  
4:    list_t *fast = start;  
5:    while(slow != NULL && fast != NULL && fast->next != NULL)  
6:    {  
7:      slow = slow->next;  
8:      fast = fast->next->next;  
9:      if ( slow == fast)  
10:      {  
11:        printf("Loop detected\n");  
12:        return;  
13:      }  
14:    }  
15:    printf("No loop\n");  
16:    return;  
17:  }  

No comments:

Post a Comment