From 8e51010d2e98b1ca42aeb01c7c8cfc7c38fe6d6e Mon Sep 17 00:00:00 2001 From: vil02 Date: Sun, 17 Sep 2023 19:08:01 +0200 Subject: [PATCH] fix: add and use function `deleteList` to remove memory leak --- .../get_size_of_linked_list.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/operations_on_datastructures/get_size_of_linked_list.cpp b/operations_on_datastructures/get_size_of_linked_list.cpp index 84f8db07fb8..3c0457d3f73 100644 --- a/operations_on_datastructures/get_size_of_linked_list.cpp +++ b/operations_on_datastructures/get_size_of_linked_list.cpp @@ -16,6 +16,20 @@ int getSize(Node *root) { return 1 + getSize(root->next); } +/* + * @brief This function dealocates memory related to the given list + * It recursively deletes all of the nodes of the input list. + * @param room the root/head of the input list + * @warning Plese note that the memory for each node has to be alocated using new. + */ +void deleteList(Node *const root) { + if (root != NULL) + { + deleteList(root->next); + delete root; + } +} + int main() { Node *myList = new Node(0, NULL); // Initializes the LinkedList Node *temp = myList; @@ -31,6 +45,8 @@ int main() { std::cout << getSize(myList) << std::endl << getSize(secondList) << std::endl << getSize(thirdList) << std::endl; + deleteList(secondList); + deleteList(myList); return 0; }