RAII-style C++ class for linked list Nodes

﹥>﹥吖頭↗ 提交于 2019-12-04 10:40:26

If writing an object-oriented class to handle linked lists in C++, do you have to have a LinkedList (manager) class which handles the deletion of the list nodes in its destructor?

No, the structure is defined by the links between nodes, so there's no need for a separate manager object. It can sometimes be more convenient to have one, especially if you're designing a library like the STL and want all the containers to have a similar interface, but you can certainly implement a linked list with just a node type.

If not, how would you deal with destruction of Nodes?

One way to avoid recursion is to remove each node from the list before deleting it, something like:

~node() {
    while (node * victim = next) {
        next = victim->next;
        victim->next = nullptr;
        delete victim;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!