What is causing runtime error in my code

Question Link: MISSP Problem - CodeChef

My Solution:
#include <stdio.h>
typedef struct typedoll
{
int type;
struct typedoll *next;
}typedoll;
int main(void) {
int test_case, n;
scanf("%d", &test_case);
while(test_case--)
{
typedoll *start = NULL;
typedoll *current = NULL;
scanf("%d", &n);
while(n--)
{
typedoll *newtype = (typedoll*)malloc(sizeof(typedoll));
scanf("%d", &newtype->type);
newtype->next = NULL;
if(start == NULL)
{
start = newtype;
current = newtype;
}
else
{
current->next = newtype;
current = newtype;
}
}
typedoll *second = start->next;
typedoll *follow = start;
while(1)
{
if(start->type != second->type)
{
second = second->next;
follow = follow->next;
}
else
{
typedoll *temp = start;
typedoll *temp2 = second;
if(start->next == second)
{
start = second->next;
follow = start;
second = start->next;
}
else
{
start = start->next;
follow->next = second->next;
second = start->next;
}
free(temp);
free(temp2);
}
if(start->next == NULL)
{
printf("%d\n", start->type);
free(second);
free(follow);
break;
}
else if(second == NULL)
{
printf("%d\n", start->type);
free(second);
free(follow);
break;
}
}
}
return 0;
}

Although shorter solutions are available. But as I’m new to the concept of linked lists, I would like to know what’s the bug here causing a runtime error.

It is probably because of an infinite loop, so check your break conditions and make sure that there is no case where it doesnt break

1 Like

Consider the test input:

1
1
1
1 Like

Hi, I added the following piece just before ‘‘if(start->type != second->type)’’ condition to handle the case in which only one doll is present. It correctly displayed the desired output but still, I’m getting a runtime error.

if(second == NULL)
        {
            printf("%d\n", start->type);
            break;
        }

Could you please look into it as to what is giving runtime error? It would be a great help.