Program to Implement Circular Queue in Data Structures (C plus plus)
Program to Implement Circular Queue in Data Structures (C plus plus)
In this tutorial, we will learn about Program to Implement Circular Queue in Data Structures (C plus plus).
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
/*C++ Program to Implement Circular Queue*/ #include <iostream> #define MAX 5 using namespace std; class circular_queue { private: int *cqueue_arr; int front, rear; public: circular_queue() { cqueue_arr = new int [MAX]; rear = front = -1; } /*Insert into Circular Queue*/ void insert(int item) { if ((front == 0 && rear == MAX-1) || (front == rear+1)) { cout<<"Queue overflowed "<<endl; return; } if (front == -1) { front = 0; rear = 0; } else { if (rear == MAX - 1) rear = 0; else rear = rear + 1; } cqueue_arr[rear] = item ; } /*Delete from Circular Queue*/ void delet() { if (front == -1) { cout<<"Queue underflowed "<<endl; return; } cout<<"Value removed from queue is : "<<cqueue_arr[front]<<endl; if (front == rear) { front = -1; rear = -1; } else { if (front == MAX - 1) front = 0; else front = front + 1; } } /*Show Circular Queue*/ void show()
{ int front_pos = front, rear_pos = rear; if (front == -1) { cout<<endl<<"Empty queue"<<endl; return; } cout<<endl<<"Values in queue are :"<<endl; if (front_pos <= rear_pos) { while (front_pos <= rear_pos) { cout<<cqueue_arr[front_pos]<<" "; front_pos++; } } else { while (front_pos <= MAX - 1) { cout<<cqueue_arr[front_pos]<<" "; front_pos++; } front_pos = 0; while (front_pos <= rear_pos) { cout<<cqueue_arr[front_pos]<<" "; front_pos++; } } cout<<endl; } }; int main() { int ch, value; circular_queue cq; do { cout<<"1. Insert into the queue "<<endl; cout<<"2. Delete from the queue "<<endl ; cout<<"3. Display queue "<<endl; cout<<"4. Quit "<<endl; cout<<"Please enter your choice : "; cin>>ch; switch(ch) { case 1: cout<<"Please enter the value for insertion in queue : "; cin>>value; cq.insert(value); break; case 2: cq.delet(); break; case 3: cq.show(); break; case 4: break; default: cout<<"Please enter a valid option"<<endl; } } while(ch != 4); return 0; } |
Output: