From 8df7a884f501ca650d08d9942fe3b6e47545592a Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Sat, 14 Sep 2024 01:39:03 +0200 Subject: [PATCH] fix: remove memory leak from `circular_queue_using_linked_list.cpp` (#2731) --- .../circular_queue_using_linked_list.cpp | 56 ++++++++++++------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/data_structures/circular_queue_using_linked_list.cpp b/data_structures/circular_queue_using_linked_list.cpp index 3d92b3b3ebe..41b55926430 100644 --- a/data_structures/circular_queue_using_linked_list.cpp +++ b/data_structures/circular_queue_using_linked_list.cpp @@ -5,11 +5,21 @@ struct node { struct node* next; }; class Queue { - node* front=nullptr; - node* rear=nullptr; + node* front = nullptr; + node* rear = nullptr; -public: - Queue() = default; + Queue(const Queue&) = delete; + Queue& operator=(const Queue&) = delete; + + public: + Queue() = default; + ~Queue() { + while (front) { + dequeue(); + } + } + + private: void createNode(int val) { auto* nn = new node; nn->data = val; @@ -17,13 +27,13 @@ class Queue { front = nn; rear = nn; } + + public: void enqueue(int val) { if (front == nullptr || rear == nullptr) { createNode(val); - } - else { - node* nn; - nn = new node; + } else { + node* nn = new node; nn->data = val; rear->next = nn; nn->next = front; @@ -31,23 +41,29 @@ class Queue { } } void dequeue() { - node* n; - n = front; - if (n) { + if (front == nullptr) { + return; + } + const node* const n = front; + if (front == rear) { + front = nullptr; + rear = nullptr; + } else { front = front->next; - delete n; + rear->next = front; } + delete n; } void traverse() { - node* ptr; - ptr = front; - if (ptr) { - do { - std::cout << ptr->data << " "; - ptr = ptr->next; - } while (ptr != rear->next); - std::cout << front->data << std::endl; + if (front == nullptr) { + return; } + const node* ptr = front; + do { + std::cout << ptr->data << ' '; + ptr = ptr->next; + } while (ptr != front); + std::cout << '\n'; } }; int main(void) {