Saturday, April 23, 2011

Queue Circular

#include "conio.h"
#include "stdio.h"
#include "stdlib.h"

#define MAX 5

struct cqueue
{
int info[MAX];
int front, rear, count;
} cq;

int main(void)
{
int ch, n;
cq.front = 0;
cq.rear = -1;
cq.count = 0;
while(1)
{
clrscr();
f_disp(&cq);
printf("\n\n1. Enqueue \n2. Dequeue\n3. Display\n4. Exit.");
printf("\nEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter info : ");
scanf("%d",&n);
enqueue(&cq, n);
break;
case 2: n = dequeue(&cq);
if(n!=-1)
{
printf("Dequeued : %d",n);
getch();
}
else
{
printf("Queue underflow...");
getch();
break;
}
break;
case 3: disp(&cq);
break;
case 4: exit(0);
default: printf("Invalid choice. \nPlease enter 1-4");
}
}

getch();
return 0;
}

/* add node to queue list */
enqueue(struct cqueue *q, int n)
{
if(q->count == MAX)
{
printf("\nQueue overflow...");
getch();
return;
}
q->rear = (q->rear+1)%MAX;
q->info[q->rear] = n;
q->count++;
}

/* delete node from queue list */
dequeue(struct cqueue *q)
{
int n;
if(q->count==0)
{
printf("Queue underflow...");
getch();
return -1;
}

n = q->info[q->front];
q->front = (q->front+1)%MAX;
q->count--;
return n;
}


/* display items of queue */
disp(struct cqueue *q)
{
int i, n = q->count;
clrscr();
if(n == 0)
{
printf("No item...");
getch();
return;
}
else
{
printf("\n\n\tQueue are : \n");
for(i=q->front;n>0;n--)
{
printf("\t\t\t%d\n ", q->info[i]);
i = (i+1)%MAX;
}
}
printf("\n\nPress any key to return to main menu...");
getch();

}

/*display items on head of menu display. */
f_disp(struct cqueue *q)
{
int i, n = q->count;
if(n == 0)
{
printf("No item...");
return;
}
printf("Queue are : \n\t\t");
for(i=q->front;n>0;n--)
{
printf("%d, ", q->info[i]);
i = (i+1)%MAX;
}
}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites