Simetrical wrote:It has to be singly-linked, I guess, but then what's with prev? It has to be some kind of local variable
Yup, prev is a local variable. When traversing a singly linked list and you get to the node of interest, you need to keep a local variable pointing to the previous node. If you keep only a single variable pointing to the current node, then you have no way of hooking the previous node to the next node, because you lose your pointer to the previous node once you decided it's not the node you want to delete.
There is a way around that (testing currentNode->next as opposed to testing currentNode), but in the end you still need a second local variable to point to some
node. You either hold onto the toDelete node so you can delete it after rearranging the linked list, or you hold onto toDelete->next so you can delete using currentNode->next and rearrange the linked list after deleting the node.
DeGuerre wrote:I feel compelled to point out that in a professional C++ shop, this code would not pass review. In fact, it's considered quite evil these days to write an explicit "delete".
Really. So what do you do instead? Depend on some kind of garbage collection? (I honestly don't know. I haven't done much with C++ since school.)
I believe you would depend on the programmer to design a class which appropriately deletes dynamically allocated memory when the destructor of the object is called. Then, either the compiler will invoke your destructor implicitly during the function epilogue, or the programmer can invoke the destructor explicitly.
Even with garbage collection, C# still uses the latter method on occasion. In fact, all C# objects have a method called Dispose, which is in essence a destructor. Particularly when using .NET graphical capabilities, MS highly suggests explicitly calling Dispose on any GDI+ objects.