fork(3) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6. int data;
  7. struct node *next;
  8. };
  9.  
  10. int detectLoop(struct node *head)
  11. {
  12. struct node *fastPtr, *slowPtr;
  13. for(fastPtr=head, slowPtr=head; fastPtr&&fastPtr->next;)
  14. {
  15. fastPtr = fastPtr->next->next;
  16. slowPtr = slowPtr->next;
  17. if (fastPtr == slowPtr) return 1;
  18. }
  19. return 0;
  20. }
  21.  
  22. void push(struct node** head, int new_data)
  23. {
  24. /* create temp node */
  25. struct node* temp = (struct node*) malloc(sizeof(struct node));
  26. temp->data = new_data;
  27. temp->next = (*head);
  28. (*head) = temp;
  29. }
  30.  
  31. int main()
  32. {
  33. struct node* head = NULL;
  34. push(&head, 10);
  35. push(&head, 3);
  36. push(&head, 5);
  37. push(&head, 20);
  38. push(&head, 50);
  39. /* Create a loop for testing */
  40. head->next->next->next->next->next = head->next;
  41.  
  42. if(detectLoop(head))
  43. printf("Found Loop\n");
  44. else
  45. printf("Not Found");
  46. return 0;
  47. }
  48.  
  49.  
Success #stdin #stdout 0s 4164KB
stdin
Standard input is empty
stdout
Found Loop