CuriousProgrammer70184
CuriousProgrammer70184

Reputation: 539

How can I remove a dynamically added node from memory?

I have a node in a linked list defined as:

class Node {
public:
    Node* next = nullptr;
    int value;
};

I am inserting nodes into the list as:

void insertNode(Node* &head, int value) {

    Node* newNode = new Node;
    newNode->value = value;
    newNode->next = head;

    head = newNode;
}

I want to remove some node in that list in another function

void deleteNode(Node* head) {
    // ...
}

How can I remove that now unused node from memory?

Upvotes: 1

Views: 47

Answers (1)

Jesper Juhl
Jesper Juhl

Reputation: 31459

You'd remove a node by 1) deleteing it. 2) adjusting the previous node to point to the one following the deleted node (or nullptr if the deleted node was the last one).

Upvotes: 1

Related Questions