-
about linked lists
hi
i just have one question regarding linked lists.
In the cprogramming.com tutorial about simple linked lists, they show this while loop to traverse all the nodes of the linked list ( i put the printf):
Code:
while (conductor->next != NULL){ printf("Valor: %d\n", conductor->value); conductor = conductor->next; }
my question is: Why the while condition:
conductor->next != NULL, will work, and the conductor != NULL won't. I tried the last condition and all the data in the nodes were printed, but i got a Segmentation Fault error at the last.
Thanks in advance..
-
> conductor->next != NULL, will work, and the conductor != NULL won't.
That would depend on how well you constructed the linked list in the first place.
If you were sloppy about setting next pointers when you built the list, you could be having all sorts of problems.
-
conductor->next is pointer to next element in a linked list. So only next pointer found Null should be working. not like the whole conductor found Null after all.
-
>So only next pointer found Null should be working.
Not necessarily. As long as you have another reference into the list (root, for example, from the tutorial) you can walk conductor off the end:
Code:
conductor = root;
while ( conductor != NULL ) {
printf ( "%d\n", conductor->value );
conductor = conductor->next;
}
Provided you don't ever actually dereference the null pointer, everything is kosher. If root isn't a valid reference to the list, you will have problems though. That's why the tutorial always makes sure to create a root node before doing anything else.
>but i got a Segmentation Fault error at the last.
Post the code you've been using. It's quite likely that you didn't build the list properly.
-
Neither of these checks will work if you have a circular list.
Quzah.