nikunjsoni

142

Mar 17th, 2021
103
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode(int x) : val(x), next(NULL) {}
  7.  * };
  8.  */
  9. class Solution {
  10. public:
  11.     ListNode *detectCycle(ListNode *head) {
  12.         ListNode *slow, *fast;
  13.         slow = head;
  14.         fast = head;
  15.         bool cyclePresent = false;
  16.         while(fast && fast->next){
  17.             slow = slow->next;
  18.             fast = fast->next->next;
  19.             if(slow == fast){
  20.                 cyclePresent = true;
  21.                 break;
  22.             }
  23.         }
  24.         if(!cyclePresent) return NULL;
  25.         slow = head;
  26.         while(slow != fast){
  27.             slow = slow->next;
  28.             fast = fast->next;
  29.         }
  30.         return slow;
  31.     }
  32. };
RAW Paste Data