Advertisement
Guest User

Check Cyclic Linked List

a guest
Dec 21st, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <assert.h>
  3.  
  4. typedef struct Node {
  5.     Node* next;
  6. } Node;
  7.  
  8. bool checkCylic (Node* head) {
  9.     Node* slow = head;
  10.     Node* fast = head;
  11.     if (head == NULL) return true;
  12.     while (fast->next != NULL) {
  13.         slow = slow->next;
  14.         fast = fast->next;
  15.         if (fast->next != NULL) {
  16.             fast = fast->next;
  17.         } else return false;
  18.         if (fast == slow) return true;
  19.     }
  20.     return false;
  21. }
  22.  
  23. int main ()
  24. {
  25.     Node head1, node1;
  26.     head1.next = &node1;
  27.     node1.next = NULL;
  28.  
  29.     Node head2, node2, node3, node4;
  30.     head2.next = &node2;
  31.     node2.next = &node3;
  32.     node3.next = &node4;
  33.     node4.next = &node3;
  34.  
  35.     assert (checkCylic(&head1) == false);
  36.     assert (checkCylic(&head2) == true);
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement