Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
gr33kbo1 Avatar asked Dec 01 '22 03:12

gr33kbo1


2 Answers

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

like image 150
Natan Streppel Avatar answered Dec 05 '22 07:12

Natan Streppel


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.

like image 39
Pierre Fourgeaud Avatar answered Dec 05 '22 06:12

Pierre Fourgeaud