Linked list cycle detection


  • 1
    A

    int cycle(struct ListNode *head){
    int s1=1,f1=1;
    struct ListNode *slow,*fast;
    slow=head;
    fast=head;
    while(fast&&fast->next)
    {
    slow=slow->next;
    s1=s1+1;
    fast=fast->next->next;
    f1+=2;
    if(slow==fast)
    return (f1-s1);
    }

    return -1;
    

    }
    class Solution {
    public:
    ListNode *detectCycle(ListNode *head) {

        ListNode *slow,*fast;
        int k;
         slow=fast=head;
         if(head==NULL)
             return NULL;
          k=cycle(head);
          if(k==-1)
              return NULL;
         while(k--!=0)
           fast=fast->next;
        while(slow!=fast)
        {
            slow=slow->next;
            fast=fast->next;
         }
        
        return slow;
    }
    

    };


  • 0
    A

  • 0
    S

    so amazing code yrr....................


  • 0
    S
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.