File tree 1 file changed +24
-27
lines changed
1 file changed +24
-27
lines changed Original file line number Diff line number Diff line change 2
2
3
3
struct node {
4
4
int data;
5
- struct node * next;
5
+ struct node * next;
6
6
};
7
7
class Queue {
8
- node * front;
9
- node * rear;
8
+ node* front= nullptr ;
9
+ node* rear= nullptr ;
10
10
11
- public:
12
- Queue () {
13
- front = NULL ;
14
- rear = NULL ;
15
- }
11
+ public:
12
+ Queue () = default ;
16
13
void createNode (int val) {
17
- node *ptr;
18
- node *nn;
19
- nn = new node;
20
- ptr = front;
14
+ auto * nn = new node;
21
15
nn->data = val;
22
- nn->next = NULL ;
16
+ nn->next = nullptr ;
23
17
front = nn;
24
18
rear = nn;
25
19
}
26
20
void enqueue (int val) {
27
- if (front == NULL || rear == NULL ) {
21
+ if (front == nullptr || rear == nullptr ) {
28
22
createNode (val);
29
- } else {
30
- node *ptr;
31
- node *nn;
32
- ptr = front;
23
+ }
24
+ else {
25
+ node* nn;
33
26
nn = new node;
34
27
nn->data = val;
35
28
rear->next = nn;
@@ -38,19 +31,23 @@ class Queue {
38
31
}
39
32
}
40
33
void dequeue () {
41
- node * n;
34
+ node* n;
42
35
n = front;
43
- front = front->next ;
44
- delete (n);
36
+ if (n) {
37
+ front = front->next ;
38
+ delete n;
39
+ }
45
40
}
46
41
void traverse () {
47
- node * ptr;
42
+ node* ptr;
48
43
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
+ }
54
51
}
55
52
};
56
53
int main (void ) {
You can’t perform that action at this time.
0 commit comments