I have the following code which iteratively reverses a linked list.
struct list {
int elem;
list *next;
};
/* .... */
void ReverseListIterative(list **listref)
{
list *currNode = *listref;
list *prevNode = NULL;
list *nextNode = NULL;
while(currNode) {
*listref = currNode;
nextNode = currNode->next;
currNode->next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
}
In the code, currNode,prevNode and nextNode are all pointers local to ReverseListIterative(). How come the original list still gets modified (gets reversed, to be more precise) ? Should’nt we be using
list **currNode;
list **prevNode;
list **nextNode;
so that actual addresses of the list nodes get modified ?
No we shouldn’t.
You don’t want to change the addresses of the nodes in memory (which means changing their location), but rather how they are pointing to each other, i.e: to which node does each node point, and this is done by changing the
nextwhich happens in these lines:If we use
list **currNode, I should be saying:But what did that benefit me?
We’re only changing how the nodes are connected to each other, and the connections are
nextin each node, so only the values of them should be changed.Hope that’s clarifying enough 🙂