Queue Implementation using Structure
Table of Content:
Like stacks, queues are lists. With a queue, however, insertion is done at one end, whereas deletion is performed at the other end. Queue implementation using structure are given below
The basic operations on a queue are enqueue, which inserts an element at the end of the list (called the rear), and dequeue, which deletes (and returns) the element at the start of the list (known as the front).
Insert into queue function
void insert() { int item; printf("Element : "); scanf("%d",&item); if(front==(rear+1)%3) { printf("Queue is Full"); return; } if(front==-1) { rear=front=0; } else { rear=(rear+1)%3; } cque.cqueue[rear]=item; printf("Successfully Insert"); }
Delete into queue function
void del() { int num; if(front==-1) { printf("Queue Empty"); return; } else { num=cque.cqueue[front]; printf("Deleted item : %d",num); } if(front==rear) { front=-1; } else front=(front+1)%3; }
Display from queue
void display() { int i; if(front==-1) { printf("Queue Empty"); return; } else { printf("\n\nItems : "); for(i=front;i<=rear;i++) { printf(" %d",cque.cqueue[i]); } } }
program of queue using structure
/*** program of queue ****/ #include#include void insert(); void del(); void display(); struct circ { int cqueue[5]; }; struct circ cque; int rear=0,front=-1; void main() { while(1) { int num; //clrscr(); printf("\n1.Insertion\n2.Deletion\n3.Display\n0.Exit\n"); printf("\n\nSelect Option : "); scanf("%d",&num); switch(num) { case 1: insert(); break; case 2: del(); break; case 3: display(); break; case 0: exit(0); break; default: printf("\n\nInvalid Option "); } getch(); } } void insert() { int item; printf("Element : "); scanf("%d",&item); if(front==(rear+1)%3) { printf("Queue is Full"); return; } if(front==-1) { rear=front=0; } else { rear=(rear+1)%3; } cque.cqueue[rear]=item; printf("Successfully Insert"); } void del() { int num; if(front==-1) { printf("Queue Empty"); return; } else { num=cque.cqueue[front]; printf("Deleted item : %d",num); } if(front==rear) { front=-1; } else front=(front+1)%3; } void display() { int i; if(front==-1) { printf("Queue Empty"); return; } else { printf("\n\nItems : "); for(i=front;i<=rear;i++) { printf(" %d",cque.cqueue[i]); } } }