So I’m playing around with linked lists, trying to get my brain around them, and I decided to add “ordinal” values to each node in my list. This way, I can delete by ordinal rather than value, and do some other cool stuff later on.
Only, when I delete an element from the list all the ordinals get thrown out of whack (fairly obvious, that), so I thought “ok, I’ll just run up the list in a different function, resetting all of the ordinals”. I could technically start this function at the element that got deleted and pass it in the ordinal from that node to save time, as the previous nodes should be untouched, but for now I’m doing it the less elegant way because I said so.
“What is your question?”. I knew you’d ask that! “Get on with it!” I knew you’d say that!
The test program, which I can link to or include here, just creates a list of 5 nodes, removes the 3rd node and then adds a node onto the end.
The expected output is: DEBUG: resetting ordinals: 0 1 2 3 4
The actual output is: DEBUG: resetting ordinals: 1 2 4 5 5
So, without any further ado, here is my question: Why is the actual output different from my expectations?
void ll_fix(node_t* list)
{
node_t* root = list;
int ordinal = 0;
printf("DEBUG: resetting ordinals: ");
while(list->next != NULL)
{
list->ordinal = ordinal;
list = (node_t*)list->next;
printf("%d ",list->ordinal);
ordinal++;
}
printf("%d\n",list->ordinal);
list = root; // rewind the list
}
You are printing the ordinal before the change to it. So you see the previous values.
Should probably be:
This will not change the last value though, a better fix is: