Why my code is wrong?


  • 0
    W
    ListNode *detectCycle(ListNode *head) {
    	ListNode* fast = head;
    	ListNode* slow = head;
    	ListNode* finder = head;
    
    	while (true)
    	{
    		if (fast&&fast->next)
    		{
    			fast = fast->next->next;
    			slow = slow->next;
    		}
    		else
    		{
    			return NULL;
    		}
    		if (fast == slow)
    			break;
    	}
    	while (true)
    	{
    		slow = slow->next;
    		finder = finder->next;
    		if (slow == finder)
    		{
    			return finder;
    		}
    	}
    }
    

    the message is:
    Input:
    [1,2]
    tail connects to node index 0

    Output:
    tail connects to node index 1

    Expected:
    tail connects to node index 0


  • 0
    B

    The last while loop needs to check if the slow and finder are the same before moving to the next node. This will allow for when both pointers are point to the first element in the node list to hbe properly returned, and not return the cyclical link node

    while (slow != finder)
    {
    slow = slow->next;
    finder = finder->next;
    }
    return finder;


Log in to reply
 

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