Defining a memory cell by
struct node {
int item;
node *next;
};
and assuming ptr
is pointing to a linked list, is there a difference between putting while(ptr!=NULL)
vs while(ptr->next!=NULL)
to loop through the list until reaching the null pointer?
while(ptr->next!=NULL)
won't loop through your last node.
By the time you get to your last node, ptr->next
will be null, and it will get out of the while
loop
while(ptr != NULL)
will iterate on all your linked list when while(ptr->next != NULL)
will skip the last element.
The second solution is useful when you want to access your last node to add a new element at the end of the list for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With