Tuesday, April 6, 2010

ds - enqueue and dequeue implementation in linear queue

#include"stdio.h"
#include"conio.h"
#include"alloc.h"
#include"stdlib.h"
#define n 8
struct queue
{
int f;
int r;
int data;
int a[n];
};
typedef struct queue queue;
void display(queue *);
void enqueue(queue **,int);
void dequeue(queue **);
void main()
{
queue *q=NULL;
clrscr();
q->f=-1;
q->r=-1;
enqueue(&q,10);
enqueue(&q,20);
enqueue(&q,30);
enqueue(&q,40);
enqueue(&q,50);
enqueue(&q,60);
display(q);
dequeue(&q);
display(q);
enqueue(&q,70);
printf("\n");
display(q);
getch();
}
void enqueue(queue **q,int d)
{
int i;
if((*q)->r==n-1&&(*q)->f==0)
{printf("memory overflow");
exit(0);}
if((*q)->f==-1&&(*q)->r==-1)
{
(*q)->r=0;
(*q)->f=0;
}
else{
if((*q)->r==n-1)
{
i=(*q)->f;
while(i<=(*q)->r) {
(*q)->a[i-(*q)->f]=(*q)->a[i];
i++; }
(*q)->r=(*q)->r-(*q)->f+1;
(*q)->f=0;
}
else
(*q)->r=(*q)->r+1;
}
(*q)->a[(*q)->r]=d;
}
void display(queue *q)
{ int t=q->f;
while(t {printf("%d ",q->a[t]);
t++;
}
}
void dequeue(queue **q)
{
int y;
if((*q)->f==-1&&(*q)->r==-1)
{printf("memory overflow");
exit(0);}
y=(*q)->a[(*q)->f];
if((*q)->f==(*q)->r)
{(*q)->a[(*q)->f]=0;
(*q)->f=-1;
(*q)->r=-1; }
else{
(*q)->a[(*q)->f]=0;
(*q)->f=(*q)->f+1; }
printf("\n%d deleted\n",y);
}

No comments:

Post a Comment