I have a struct like the one below and I create pointer objects base on it, for example, "Node* prvNode = previous;". The creation of these objects are made in several functions (I am implementing a doubly linked list) where I insert and delete nodes from such a list. I suppose I should somehow "delete" or "destroy" the nodes that I delete to de-allocate memory. Is this correct? If so, how can I do it?
struct Node {
int data; // each node holds an integer data
Node* previous; // pointer to the previous node
Node* next; // pointer to the next node
Node(int d = 0, Node* prv = NULL, Node* nxt = NULL) : data(d), previous(prv), next(nxt) {}
Node* get_previous() const { return previous; }
Node* get_next() const { return next; }
Node* insert_before(int d); // insert the int before this node
// return a pointer to the inserted node
Node* insert_after(int d); // insert the int after this node
// return a pointer to the inserted node
void delete_before(); // delete the node before this node
void delete_after(); // delete the node after this node
};
1. Create a pointer variable local to the function.
2. Find the node to delete, and assign the address to the variable.
3. Change all of the relevant links (you don't want to be pointing to a node that is being deleted).
4. Then delete the node.
Thanks for the information, the instructions are clear but, how to I perform step 4? What command should I use? Is it a delete, a destructor? I am, in fact, learning how to use pointers.
Whenever you use the new command to allocate memory, you must use the corresponding delete command to free the memory. Using a delete command calls the destructor automatically.
1 2 3 4 5 6 7
//if you dynamically allocated a single object
int *ptr = newint;
delete ptr;
//if you dynamically allocated an array of objects
int *ptr = newint[100];
delete[] ptr;