Skip to content

Commit

Permalink
fix: remove memory leak from circular_queue_using_linked_list.cpp (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 authored Sep 13, 2024
1 parent 920b6d4 commit 8df7a88
Showing 1 changed file with 36 additions and 20 deletions.
56 changes: 36 additions & 20 deletions data_structures/circular_queue_using_linked_list.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,49 +5,65 @@ 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;
nn->next = nullptr;
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;
rear = nn;
}
}
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) {
Expand Down

0 comments on commit 8df7a88

Please sign in to comment.