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

Defining a memory location using

struct node {
    int item;
    node *next;
};

and assuming it ptrpoints to a linked list, is there a difference between putting while(ptr!=NULL)vs while(ptr->next!=NULL)in a loop through the list until a null pointer is reached?

+4
source share
2 answers

while(ptr->next!=NULL) will not go through your last node.

By the time you get to your last node, it ptr->nextwill be null and it will exit the loopwhile

+14
source

while(ptr != NULL)will iterate through all of your linked lists when it while(ptr->next != NULL)misses the last item.

, node, , .

+6

Source: https://habr.com/ru/post/1502485/


All Articles