Reputation: 309
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?
Upvotes: 5
Views: 15662
Reputation: 14510
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.
Upvotes: 6
Reputation: 5866
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
Upvotes: 14