Solution: much easier to be understood 35ms c++


  • 0
    J

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

        ListNode *fast=head;
        ListNode *slow=head;
        if(!head)
        return NULL;
        bool flag;
        while(1)
        {
            fast=fast->next;
            if(fast==NULL)
            return NULL;
            fast=fast->next;
            if(fast==NULL)
            return NULL;
            slow=slow->next;
            if(fast==slow)
            {flag= true;
              break;}
     
        }
        unordered_map<ListNode*,ListNode*> mymap;
        ListNode *temp=head;
        if(flag)
        {
          while(1)
          {
              if(mymap.find(temp)==mymap.end())
               mymap[temp]=temp;
              else if(mymap.find(temp)!=mymap.end())
               return temp;
               
               temp=temp->next;
              
          }
            
            
        }
        
        
        
    }
    

    };


Log in to reply
 

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