while(ptr!=NULL)

in this we always get null at the end or before

We get null at the end of our input i.e. when our entire input is exhausted.