gr33kbo1
gr33kbo1

Reputation: 309

Traversing through a linked list: while(ptr!=NULL) vs while(ptr->next!=NULL)?

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

Answers (2)

Pierre Fourgeaud
Pierre Fourgeaud

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

Natan Streppel
Natan Streppel

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

Related Questions