Skip to content

Commit 5ba8bc2

Browse files
authored
read violation resolved (TheAlgorithms#1496)
1 parent a9d3387 commit 5ba8bc2

File tree

1 file changed

+24
-27
lines changed

1 file changed

+24
-27
lines changed

data_structures/circular_queue_using_linked_list.cpp

+24-27
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,27 @@
22

33
struct node {
44
int data;
5-
struct node *next;
5+
struct node* next;
66
};
77
class Queue {
8-
node *front;
9-
node *rear;
8+
node* front=nullptr;
9+
node* rear=nullptr;
1010

11-
public:
12-
Queue() {
13-
front = NULL;
14-
rear = NULL;
15-
}
11+
public:
12+
Queue() = default;
1613
void createNode(int val) {
17-
node *ptr;
18-
node *nn;
19-
nn = new node;
20-
ptr = front;
14+
auto* nn = new node;
2115
nn->data = val;
22-
nn->next = NULL;
16+
nn->next = nullptr;
2317
front = nn;
2418
rear = nn;
2519
}
2620
void enqueue(int val) {
27-
if (front == NULL || rear == NULL) {
21+
if (front == nullptr || rear == nullptr) {
2822
createNode(val);
29-
} else {
30-
node *ptr;
31-
node *nn;
32-
ptr = front;
23+
}
24+
else {
25+
node* nn;
3326
nn = new node;
3427
nn->data = val;
3528
rear->next = nn;
@@ -38,19 +31,23 @@ class Queue {
3831
}
3932
}
4033
void dequeue() {
41-
node *n;
34+
node* n;
4235
n = front;
43-
front = front->next;
44-
delete (n);
36+
if (n) {
37+
front = front->next;
38+
delete n;
39+
}
4540
}
4641
void traverse() {
47-
node *ptr;
42+
node* ptr;
4843
ptr = front;
49-
do {
50-
std::cout << ptr->data << " ";
51-
ptr = ptr->next;
52-
} while (ptr != rear->next);
53-
std::cout << front->data << std::endl;
44+
if (ptr) {
45+
do {
46+
std::cout << ptr->data << " ";
47+
ptr = ptr->next;
48+
} while (ptr != rear->next);
49+
std::cout << front->data << std::endl;
50+
}
5451
}
5552
};
5653
int main(void) {

0 commit comments

Comments
 (0)