Problem in circular linked list

I am getting the wrong answer in two test cases. so please tell me what I am doing wrong

We use slow and fast pointers for breaking the cycle when the cycle actually exists in the list ie.,when the last
element’s next pointer points to any other element of the list. But here we are given the input in the form of a list and the cycle starts when we encounter any repeating element. So slow and fast pointer approach will not work here. Instead use this code -

node *temp = head;
node *prev, *curr;

while(temp!=NULL)
{
    curr = temp->next;
    prev = NULL;
    while(curr!=NULL)
    {
        if(temp->data==curr->data)
        {
            prev->next = NULL;
            print(head);
            return 0;
        }
        prev = curr;
        curr = curr->next;
    }
    temp = temp->next;
}
1 Like