Sunday, August 29, 2010

C Program to implement queue as an array

#include<stdio.h>
#include<conio.h>
#define MAX 10
void insertque(int *,int,int *,int*);
int deleteque(int *,int*,int*);
void main()
{
  int a[MAX];
  int front= -1,rear= -1,i;
  clrscr();
  insertque(a,20,&front,&rear);
  insertque(a,5,&front,&rear);
  insertque(a,9,&front,&rear);
  insertque(a,7,&front,&rear);
  insertque(a,22,&front,&rear);
  insertque(a,12,&front,&rear);
  insertque(a,15,&front,&rear);
  insertque(a,18,&front,&rear);
  insertque(a,10,&front,&rear);
  insertque(a,30,&front,&rear);
  insertque(a,35,&front,&rear);
  i=deleteque(a,&front,&rear);
  printf("\n Item deleted : %d",i);
  i=deleteque(a,&front,&rear);
  printf("\n Item deleted : %d",i);
  i=deleteque(a,&front,&rear);
  printf("\n Item deleted : %d",i);
  getch();
}

/* Add an element to the queue */
void insertque(int *a,int item,int *pfront,int *prear)
{
        if(*prear == MAX-1)
        {
              printf("\n Queue is full ");
              return ;
        }
        (*prear)++;
        a[*prear]=item;
        if(*pfront==-1)
        *pfront=0;
}

/* Removes an element form the queue */
int deleteque(int *a,int *pfront,int *prear)
{
    int data;
    if(*pfront==-1)
    {
        printf("\n Queue is empty ");
        return NULL;
    }
    data=a[*pfront];
    a[*pfront]=0;
    if(*pfront==*prear)
        *pfront=*prear-1;
    else
        (*pfront)++;
    return data;
}

No comments:

Post a Comment