TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
circular_queue_using_linked_list.cpp
1#include <iostream>
2
3struct node {
4 int data;
5 struct node* next;
6};
7class Queue {
8 node* front = nullptr;
9 node* rear = nullptr;
10
11 Queue(const Queue&) = delete;
12 Queue& operator=(const Queue&) = delete;
13
14 public:
15 Queue() = default;
16 ~Queue() {
17 while (front) {
18 dequeue();
19 }
20 }
21
22 private:
23 void createNode(int val) {
24 auto* nn = new node;
25 nn->data = val;
26 nn->next = nullptr;
27 front = nn;
28 rear = nn;
29 }
30
31 public:
32 void enqueue(int val) {
33 if (front == nullptr || rear == nullptr) {
34 createNode(val);
35 } else {
36 node* nn = new node;
37 nn->data = val;
38 rear->next = nn;
39 nn->next = front;
40 rear = nn;
41 }
42 }
43 void dequeue() {
44 if (front == nullptr) {
45 return;
46 }
47 const node* const n = front;
48 if (front == rear) {
49 front = nullptr;
50 rear = nullptr;
51 } else {
52 front = front->next;
53 rear->next = front;
54 }
55 delete n;
56 }
57 void traverse() {
58 if (front == nullptr) {
59 return;
60 }
61 const node* ptr = front;
62 do {
63 std::cout << ptr->data << ' ';
64 ptr = ptr->next;
65 } while (ptr != front);
66 std::cout << '\n';
67 }
68};
69int main(void) {
70 Queue q;
71 q.enqueue(10);
72 q.enqueue(20);
73 q.enqueue(30);
74 q.enqueue(40);
75 q.enqueue(50);
76 q.enqueue(60);
77 q.enqueue(70);
78 q.traverse();
79 q.dequeue();
80 q.traverse();
81 return 0;
82}
struct node { int data; int height; struct node *left; struct node *right;} node
for std::queue
Definition avltree.cpp:13
int main()
Main function.