How does the delete next works and how it deletes the whole list instead it should delete the value to which next is pointing
Try running the code in a debugger, or add print statements to the destructor, with some driving logic in main.
When it calls delete next, it dereferences next (if not null), and then triggers the destructor for next, which then recursively calls delete on the next node's next, and so on.
// Example program
#include <iostream>
#include <string>
template<typename V>
class MapNode {
public: // public to access next
std::string key;
V value {};
MapNode* next {};
MapNode() = default;
MapNode(const std::string& key_, const V& value_) : key(key_), value(value_) {}
MapNode(const MapNode&) = delete;
MapNode(MapNode&&) = delete;
MapNode& operator=(MapNode) = delete;
~MapNode() {
std::cout << "Deleting node with value " << value << '\n';
delete next;
}
};
int main()
{
{
MapNode<int> node("answer", 42);
node.next = new MapNode<int>("nintendo", 64);
node.next->next = new MapNode<int>("blocks", 17398);
} // destructor will be called automatically
std::cout << "Done.\n";
}
Personally, I like to avoid the recursive nature in this manner, and will instead have a type like "Map" that aggregates a group of MapNodes, and then just iterates through them in the Map's destructor.