Skip to content

Commit e139ee9

Browse files
fix: add and use function deleteList to remove memory leak (#2534)
Co-authored-by: realstealthninja <[email protected]>
1 parent 8a36824 commit e139ee9

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

operations_on_datastructures/get_size_of_linked_list.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,20 @@ int getSize(Node *root) {
1616
return 1 + getSize(root->next);
1717
}
1818

19+
/*
20+
* @brief This function dealocates memory related to the given list
21+
* It recursively deletes all of the nodes of the input list.
22+
* @param room the root/head of the input list
23+
* @warning Plese note that the memory for each node has to be alocated using new.
24+
*/
25+
void deleteList(Node *const root) {
26+
if (root != NULL)
27+
{
28+
deleteList(root->next);
29+
delete root;
30+
}
31+
}
32+
1933
int main() {
2034
Node *myList = new Node(0, NULL); // Initializes the LinkedList
2135
Node *temp = myList;
@@ -31,6 +45,8 @@ int main() {
3145
std::cout << getSize(myList) << std::endl
3246
<< getSize(secondList) << std::endl
3347
<< getSize(thirdList) << std::endl;
48+
deleteList(secondList);
49+
deleteList(myList);
3450

3551
return 0;
3652
}

0 commit comments

Comments
 (0)