Reputation: 953
I've written the code like this:
ptr=front;
while(ptr->link!=NULL && ptr->priority<itempriority ){
ptr=ptr->link;
}
temp->link=ptr->link;
ptr->link=temp;
return front;
The above code didn't work.
ptr=front;
while(ptr->link!=NULL && ptr->link->priority<itempriority ){
ptr=ptr->link;
}
temp->link=ptr->link;
ptr->link=temp;
return front;
This code worked perfectly.
I'm confused why my code was not working i.e. ptr->priority<itempriority
?
In short I want to know how ptr->link->priority<itempriority
is working perfectly while ptr->priority<itempriority
is not?
Upvotes: 1
Views: 65
Reputation: 7542
Consider this
1 -> 2 -> 5 -> 8
and you want to insert 3
at correct position
while(ptr->link!=NULL && ptr->priority<itempriority ){
ptr=ptr->link;
}
At the end, ptr
will be pointing to 5
.And finally you will have
1 -> 2 -> 5 -> 3 -> 8 //Wrong
The second version
while(ptr->link!=NULL && ptr->link->priority<itempriority ){
ptr=ptr->link;
}
At the end ptr
will be 2
, and finally
1 -> 2 -> 3 -> 5 -> 8 //correct
Upvotes: 4