If you're concerned about memory, I highly recommend learning to work with Valgrind http://valgrind.org/. It is a great tool. Valgrind divides memory leaks into 3 categories:
- "definitely lost" - pointer to dynamically allocated memory is lost and there is no way to recover it
- "possibly lost" - pointer to the dynamically allocated memory is pointing to the interior of a block and may be unrelated
- "still reachable" - pointer to the dynamically allocated memory still exists, but the memory was never freed at the end of the programs execution
Running Valgrind is also very simple. Here's a link to the User Manual http://valgrind.org/docs/manual/manual.html. Some useful flags when running valgrind:
--leak-check=<no|summary|yes|full>
--show-reachable=<no|yes>
Now, the way I would remove a node in a doubly-linked list is:
// if the node to be removed is the head node
if (nodeToRemove->prev == NULL) {
// reassign the head node pointer
start_ptr = nodeToRemove->next;
} else {
// correct previous node pointer
nodeToRemove->prev->next = nodeToRemove->next;
}
// if the node to be removed node is the tail node
if (nodeToRemove->next == NULL) {
// reassign the tail node pointer
end_ptr = nodeToRemove->prev;
} else {
// correct next node pointer
nodeToRemove->next->prev = nodeToRemove->prev;
}
// deallocate memory
delete(nodeToRemove);
nodeToRemove = NULL;
Just declare node *end_ptr = NULL;
after you declare start_ptr
and when you append a node to the list, make sure the end_ptr is always pointing to the end of the list... and if you're adding to the end of the list, its easy... just point the end_ptr to the node being added.
You might as well keep a tail pointer, if you always have to delete the last node. So once you have the node you want to delete, I just check if its the head/tail node, reassign the next/prev pointers, and free the memory.
Btw... I took this from my C implementation, so if the syntax is off I apologize... but the logic is there.
Hope that helps.