From: Gene on 20 Jan 2010 21:27 On Jan 18, 4:25 pm, Chad <cdal...(a)gmail.com> wrote: > On Jan 18, 12:51 pm, Paul N <gw7...(a)aol.com> wrote: > > > > > > > On 18 Jan, 18:17, Chad <cdal...(a)gmail.com> wrote: > > > > Oh yeah. I forgot that current->data is outside the loop. And this > > > reminds me that a while back I had asked a similar question on > > > comp.lang.c. I'm suspecting that there is some underlying programming > > > concept that I haven't quite grasped yet. > > > Perhaps you mean the concept of "look before you leap"? > > > For instance, if you want to find the end of a linked list, then this > > code: > > > while (thing) { thing = thing -> next; } > > > will not work because you run off the end of the list before you stop. > > And once thing is NULL, you can't do "thing = thing -> prior" to get > > back into the list again. > > Yes. Maybe I'm wrong, but wouldn't 'thing' in the while loop *get*/ > *retrieve* the value? Then 'thing = thing -> next' would not only > *get*/*retrieve* the value, but then also store that value in 'thing'.- Hide quoted text - The variable 'thing' is only a pointer that provides access to a node. It's value is of no interest. Think of it as a "handle." If thing is non NULL (same as non-zero), you can use it to get the value stored in the node, which is thing->data, and you can use it to get anothe pointer to access the following node, thing->next . If thing is NULL (zero), it can't be used to access anything. Consequently when any loop of the form while (thing) ... exits, thing mustNULL (or zero), which means it's already useless for looking at the last node in the list. You need the pointer that thing contained _just before_ you wiped out its value by advancing to the end of the list. I like to do this with two pointers: NODE *trail, *lead; for (trail = NULL, lead = head; lead != NULL; trail = lead, lead = lead->next) /* do nothing */ ; if (trail) printf("last data value was %d\n", trail->data); else printf("list was empty\n"); For trees, substitute lead = lead->left. All else remains the same. |