Concise method using unordered_set


  • 0
    P

    store the listNode pointer in unordered set
    find the listNode in set

     ListNode *detectCycle(ListNode *head) {
           if (head == NULL || head->next == NULL)
    		return NULL;
    	ListNode* p = head;
    	unordered_set<ListNode*> dt;
    	while (p)
    	{
    		if (dt.find(p) != dt.end())
    			return p;
    		dt.insert(p);
    		p = p->next;
    	}
    	return NULL;
        }
    

Log in to reply
 

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