Ali Ali - 3 months ago 8
C Question

if else statement inside while loop.(i m trying to insert a node at a given position in linked list.)

void insertM(struct node **s,int pos,int n)
{
struct node *temp,*e;
temp=(struct node *)malloc(sizeof(struct node));
temp->x=n;
temp->link=NULL;
int count=1;
e=*s;
while(e!=NULL)
{
if(count==pos)
{
temp->link=e->link;
e->link=temp;
}
else
{
e=e->link;
count++;
}

}
}


If I remove the above else statement and put its content in the while loop after the if statement, the program works. But with the else statement it doesn't work. Why? What's wrong with the else statement?

Answer

The reason why the else statement is causing an error is because when you finally find the target, count doesn't increment. Therefore, count will always equal pos and the loop never breaks. To better visualize this error, imagine trying to add a node at the first node starting at the while loop,

e is not null so loop body is executed
count == pos evaluates to true so temp is inserted after e
else statement gets skipped so count stays at 1 and e stays at the first node
e is not null so loop body is executed
count == pos evaluates to true so temp is inserted after e

As you can see, you're constantly adding temp after the front infinitely many times because count is never changing when you find the target node. To better understand these errors in the future, use a debugger.