From 2e58239646966cdb751516958eac52252a6c2bb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?micha=C5=82?= Date: Mon, 6 Mar 2023 23:00:29 +0100 Subject: [PATCH] Better memory management --- double_linked_list/DoubleLinkedList.cpp | 5 +++++ main.cpp | 1 + 2 files changed, 6 insertions(+) diff --git a/double_linked_list/DoubleLinkedList.cpp b/double_linked_list/DoubleLinkedList.cpp index 4a867be..84932e3 100644 --- a/double_linked_list/DoubleLinkedList.cpp +++ b/double_linked_list/DoubleLinkedList.cpp @@ -32,6 +32,7 @@ int DoubleLinkedList::pop() { if (size == 1) { int data = head->data; delete head; + head = nullptr; return data; } Node* nodePtr = head; @@ -41,6 +42,7 @@ int DoubleLinkedList::pop() { int data = nodePtr->next->data; delete nodePtr->next; nodePtr->next = nullptr; + size--; return data; } @@ -55,6 +57,9 @@ void DoubleLinkedList::printList() { void DoubleLinkedList::printReversed() { auto* nodePtr = head; + if (nodePtr == nullptr) { + return; + } while (nodePtr->next != nullptr) { nodePtr = nodePtr->next; } diff --git a/main.cpp b/main.cpp index 707bcdb..3feb2c4 100644 --- a/main.cpp +++ b/main.cpp @@ -25,6 +25,7 @@ void simpleDoubleLinkedListTest() { list->pop(); list->printList(); list->printReversed(); + delete list; } void simpleDynamicArrayTest() {