-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
circular_queue_using_linked_list.cpp
82 lines (77 loc) · 1.58 KB
/
circular_queue_using_linked_list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
struct node {
int data;
struct node* next;
};
class Queue {
node* front = nullptr;
node* rear = nullptr;
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 = new node;
nn->data = val;
rear->next = nn;
nn->next = front;
rear = nn;
}
}
void dequeue() {
if (front == nullptr) {
return;
}
const node* const n = front;
if (front == rear) {
front = nullptr;
rear = nullptr;
} else {
front = front->next;
rear->next = front;
}
delete n;
}
void traverse() {
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) {
Queue q;
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.enqueue(70);
q.traverse();
q.dequeue();
q.traverse();
return 0;
}