Pages

Custom Search

Wednesday, October 5, 2011

ORDINARY QUEUE:

Queue is data structure in which the first inserted element is the first deleted element. It is also known as a FIFO(First In First Out). The program implementation using structure is as follows.


/*Include the necessary header files(stdio.h, stdlib.h, conio.h)*/

#define QSIZE 5 //Maximum elements in Queue

struct tag //structure definition
{
int items[QSIZE];
int rear;
int front;
};
typedef struct tag QUEUE;

void insert();
int Delete();
void display(); //Function Prototypes

int main()
{
QUEUE q;
int element, dnum, choice;
q.rear = -1;
q.front = 0;

do
{
printf("\n\nOperations on Ordinary Queue: ");
printf("\n\n1.) INSERT");
printf("\n\n2.) DELETE");
printf("\n\n3.) DISPLAY");
printf("\n\n4.) QUIT");
printf("\n\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("\nEnter the element into queue: ");
scanf("%d", &element);
insert(&q, element); //Function call by reference
break;
case 2: dnum = Delete(&q); // Function call by reference
if(dnum != -1)
{
printf("\nDeleted element: %d", dnum);
}
break;

case 3: display(q); //Function call by value
break;
case 4: break;
default: printf("\nInvalid choice! Enter again.");
}
}while(choice!=4);
getch();
}

//Function to insert elements into the queue

void insert(QUEUE *q, int element)
{
if(q->rear == QSIZE - 1)
{
printf("\nQueue is full.");
return;
}
else
{
(q->rear)++;
q->items[q->rear] = element;
}
}

//Function to delete an element from the front of queue.

int Delete(QUEUE *q)
{
if(q->front > q->rear)
{
printf("\nQueue is empty.");
return(-1);
}
else
{
return(q->items[(q->front)++]);
}
}

//Function to display the contents of queue from front to rear.

void display(QUEUE q)
{
int i;
if(q.front > q.rear)
printf("\n\nQueue empty.");
else
{
printf("\nQueue is: \n\n");
for(i=q.front; i<=q.rear; i++ )
{
printf("%d ", q.items[i]);
}
}
}

No comments:

Custom Search