Skip to content

Instantly share code, notes, and snippets.

@jayaprasad37
Last active January 31, 2021 18:23
Show Gist options
  • Save jayaprasad37/b00c18de5fc79b8cda934f861e1f5005 to your computer and use it in GitHub Desktop.
Save jayaprasad37/b00c18de5fc79b8cda934f861e1f5005 to your computer and use it in GitHub Desktop.
Queue implementation using array
#include <iostream>
#include <string.h>
#include <typeinfo>
using namespace std;
#define MAX 5 //preprossor for array size
int myarray[MAX]; //array for the queue
int count = 0; //count to check the status of the queue
int front =-1; //front index
int rear =-1; //rear index
int isempty() //function to see if the queue is empty or not
{
if(count==0) //using count
return 1; //if empty return 1
else
return 0; //if not empty return 0
}
int isfull() //function to see if the queue is full
{
if(count == MAX) //using count
return 1; //if full return 1
else
return 0; //else return 0
}
void enqueue(int x) //function to insert element into queue
{
if(isfull()) //checking if the queue is full
{
cout<<"The queue is full, can't insert!"<<endl;
return;
}
else if(isempty()) //if queue is empty initializing the values of front and rear
{
front++;
rear++;
count++;
}
else
{
rear = (rear+1)%MAX; //incrementing the rear
count++; //incrementing the count
}
cout<<"Inserting "<<x<<" into the queue"<<endl;
myarray[rear] = x; //inserting value into the queue
}
void dequeue() //function to delete element
{
if(isempty()) //checking if the queue is empty
cout<<"The queue is already empty!"<<endl;
else //if not empty
{
cout<<"Deleting "<<myarray[front]<<" from the queue"<<endl;
front = (front+1)%MAX; //incrementing the value of front
count--; //decrementing the count (status of the queue)
if(count == 0) //when queue becomes empty, changing the values of front and rear to -1 to start over
{
front = -1;
rear = -1;
}
}
}
int frontelement() //function to display the element in the front
{
if(isempty())
{
cout<<"No elements in the queue"<<endl;
return 0 ;
}
else
{
cout<<"The value at the front is "<<myarray[front]<<endl;
return myarray[front];
}
}
void display() //function to display the element in the queue
{
if(isempty())
cout<<"There are no elements in the queue"<<endl;
else
{
cout<<"The queue has: ";
for(int i = 0; i<count ; ++i)
cout<<myarray[(i+front)%MAX]<<" ";
}
cout<<endl;
}
int main()
{
enqueue(5);
enqueue(10);
enqueue(12);
display();
enqueue(1);
enqueue(3);
display();
dequeue();
dequeue();
display();
enqueue(50);
enqueue(30);
display();
dequeue();
dequeue();
dequeue();
dequeue();
display();
enqueue(1445);
enqueue(125);
frontelement();
display();
dequeue();
dequeue();
dequeue();
dequeue();
enqueue(1445);
enqueue(125);
display();
frontelement();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment