OK, here's my attempt to make valya's answer even clearer (though I thought it was pretty good already):
Say we have this list:
// a->b->c->d->e->NULL
We start at the first node, a
, which contains a pointer (next
) to b
:
// a->b ...
The line next = current->next;
sets next
to b
(simple enough). The next line current->next = result;
does this:
// NULL<-a b ... (notice there is no longer a pointer from a to b)
Then we have result = current;
which sets result
to a
(again, simple enough). And finally, we have the all important current = next;
, which set current
to b
.
So on the next iteration of the while loop, with next
set to b
, result
set to a
, and current
set to b
, we start over:
next = current->next;
// NULL<-a<-b c ...
current->next = result;
result = current;
Then we do it again:
next = current->next;
// NULL<-a<-b<-c d ...
current->next = result;
result = current;
Once we've gotten to the last item in the linked list (e
in this example), this happens:
next = current->next; // next becomes NULL
// NULL<-a<-b<-c<-d<-e
current->next = result;
result = current; // result is now e
current = next; // current is now NULL
Now, since current
is NULL, the while loop terminates, and we are left with:
*headRef = result;
which, as you can see now, makes headRef
point to e
, treating e
as the new first item in our linked list, with e->next
pointing to d
, d->next
pointing to c
, etc.