Array implementation of queue

#include<iostream>
using namespace std ;
#include<malloc.h>

typedef struct QUEUE
{
int *array ;
int size ;
int front ;
int rear ;
}queue ;

queue* create_queue(int ) ;
queue* enqueue(queue *,int ) ;
int isQueueFull(queue *) ;
int isQueueEmepty(queue *) ;
int dequeue(queue *) ;
void display(queue *)  ;

main()
{
queue *q ;
int no ;

cout<<"\n please enter the capasity of the queue " ;
cin>>no ;
q=create_queue(no) ;

int ele,i,choice,conti ;
do
{
printf("\n 1. enqueue an element in the queue ") ;
printf("\n 2. dequeue an element from the queue ") ;
printf("\n 3. display the elements currentally present in the queue") ;
printf("\n\n please enter your choice" ) ;
cin>>choice ;
switch(choice)
{
case 1 :cout<<"\n how many elements needed to be entred in the queue" ;
cin>>no ;
cout<<"\n enter the values " ;
for(i=0;i<no;i++)
{
cin>>ele ;
q=enqueue(q,ele) ;
}
break ;
case 2 :ele=dequeue(q) ;
if(ele!=-1)
cout<<"\n dequeued element is "<<ele ;
break ;
case 3 :display(q) ;
break ;
default: cout<<"\n SORRY !!! wrong choice , please try again " ;
}
cout<<"\n please enter 1 to continue " ;
cin>>conti ;
}while(conti==1) ;
}

queue* create_queue(int no)
{
queue *q ;
q=(queue*)malloc(sizeof(queue)) ;
q->size=no ;
q->front=-1 ;
q->rear=-1 ;
q->array=(int*)malloc(q->size*sizeof(int)) ;
return q ;
}

queue* enqueue(queue *q,int ele)
{
if(isQueueFull(q))
{
cout<<"\n SORRY !!! overflow condition " ;
return q ;
}
if(isQueueEmepty(q))
{
q->front++ ;
q->rear++ ;
q->array[q->rear]=ele ;
return q ;
}
q->rear=(q->rear+1)%q->size ;
q->array[q->rear]=ele ;
return q ;
}

int isQueueFull(queue *q)
{
if((q->rear+1)%q->size==q->front)
return 1 ;
return 0 ;
}

int isQueueEmepty(queue *q)
{
if(q->front==-1&&q->rear==-1)
return 1 ;
return 0 ;
}

int dequeue(queue *q)
{
if(isQueueEmepty(q))
{
cout<<"\n SORRY !!! underflow condition " ;
return -1 ;
}

int ele ;
if(q->front==q->rear)
{
ele=q->array[q->front] ;
q->front=-1 ;
q->rear=-1 ;
return ele ;
}

ele=q->array[q->front] ;
q->front=(q->front+1)%q->size ;
return ele ;
}

void display(queue *q)
{
if(isQueueEmepty(q))
{
cout<<"\n SORRY !!! underflow condition " ;
return ;
}

int curr ;
curr=q->front ;
while(curr!=q->rear)
{
cout<<q->array[curr]<<" " ;
curr=(curr+1)%q->size ;
}
cout<<q->array[q->rear]<<" " ;
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )