spider68

Linked List Cycle II

May 27th, 2020
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.54 KB | None | 0 0
  1. ListNode *detectCycle(ListNode *head) {
  2.         if(!head||!head->next)return NULL;
  3.         ListNode*slow=head,*fast=head;
  4.         int flag=0;
  5.         while(slow!=NULL&&fast!=NULL)
  6.         {
  7.             if(!fast||!fast->next)return NULL;
  8.             slow=slow->next;
  9.             fast=fast->next->next;
  10.             if(slow==fast){flag=1; break;}
  11.         }
  12.         if(flag==0)return NULL;
  13.         slow=head;
  14.         while(slow!=fast)
  15.         {
  16.             slow=slow->next;
  17.             fast=fast->next;
  18.         }
  19.         return slow;
  20.     }
Add Comment
Please, Sign In to add comment