I’m working with a linked list and am trying to initalize two pointers equal to the “first”/”head” pointer. I’m trying to do this cleanly in a for loop. The point of all this being so that I can run two pointers through the linked list, one right behind the other (so that I can modify as needed)…
Something like:
//listHead = main pointer to the linked list
for (blockT *front, *back = listHead; front != NULL; front = front->next)
//...//
back = back->next;
The idea being I can increment front early so that it’s one ahead, doing the work, and not incrementing “back” until the bottom of the code block in case I need to backup in order to modify the linked list…
Regardless as to the “why” of this, in addition to the above I’ve tried:
for (blockT *front = *back = listHead; /.../
for (blockT *front = listHead, blockT *back = listHead; /.../
I would like to avoid pointer to a pointer. Do I just need to initialize these before the loop?
The syntax is:
You’ll need the special case for
previousin the loop, in order totest and avoid backing up before the front of the list. Alternatively,
you may be able to use
&listHead, instead ofNULL, but you’ll needto play type games with it (and be sure you don’t try and modify any
members). If all you need is to be able to insert intermediate members
(in front of
front), or deletefront, then you should consider apointer to a pointer:
In the loop, you remove current from the list by
*previousNext =(making sure to advance¤t->next
currentbefore deleting theold element); to insert a new element,
*previousNext = new BlockT;.previousNext->next = current;