Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active June 27, 2019 10:37
Show Gist options
  • Save manojnaidu619/5fc24aa60253733f43889eccbdc1f3dc to your computer and use it in GitHub Desktop.
Save manojnaidu619/5fc24aa60253733f43889eccbdc1f3dc to your computer and use it in GitHub Desktop.
Circular Queue implementation using Array in CPP
#include <iostream>
using namespace std;
struct Queue{
int size;
int front;
int rear;
int *Q;
};
typedef struct Queue queue;
void create(queue *p, int size){
p->size = size;
p->front=0;
p->rear=0; // in Linear Queue, front = rear = -1
p->Q = new int[p->size];
}
void enqueue(queue *p, int ele){
if((p->rear+1)%p->size == p->front){ // In linear Queue, (p->rear >= p->size-1)
cout << "Queue is full!" << endl;
return;
}
p->rear = (p->rear+1)%p->size; // This line is added in Circular queue
p->Q[p->rear] = ele;
}
void dequeue(queue *p){
if((p->rear) == p->front){
cout << "Queue is Empty!";
return;
}
p->front = (p->front+1)%p->size ; // This line is added in Circular queue
}
void display(queue *p){
if(p->rear == p->front){
cout << "Queue is Empty!" << endl;
return;
}
int i = p->front+1;
do{
cout << p->Q[i] << " ";
i=(i+1)%p->size;
}while(i!=(p->rear+1)%p->size); // upto front == rear
}
void get_rear(queue *p){
if(p->front !=0 || p->rear !=0)
cout << endl << "Rear : " << p->Q[p->rear] << endl;
return;
}
int main(){
struct Queue q;
int size = 15;
create(&q,size);
for(int i=1;i<=10;i++){
enqueue(&q,i);
}
display(&q);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment