1) Static Implementation of linear queue:
A Queue is implemented statically by using an array of size MAX to hold elements and two integers called front and rear. A queue is a single entity that is a structure made up of the array, rear and front. Elements are added from rear end of the queue and can be deleted from front end of the queue. The ‘front’ stores the position of the current front element and ‘rear’ stores the position of the current rear element of the queue. The Queue elements can be integers, characters, strings or user defined types.
#include<stdio.h> #define MAXSIZE 30 typedef struct queue { int data[MAXSIZE]; int front,rear; }QUEUE;
void initqueue(QUEUE *pq) { pq->front=pq->rear=-1; }
int isfull(QUEUE *pq) { if(pq->rear==MAXSIZE-1) return 1; return 0; }
int isempty(QUEUE *pq) { return(pq->front==pq->rear); }
void addq(QUEUE *pq, int num) { pq->data[++pq->rear]=num; }
int removeq(QUEUE *pq) { int num; ++pq->front; num=pq->data[pq->front]; return num; //return pq->data[++pq->front]; } int main() { QUEUE q;//create int choice, num; initqueue(&q); do { printf("\n1: ADD\n2: REMOVE\n3: EXIT"); printf("\nEnter your choice"); scanf("%d",&choice); switch(choice) { case 1: if(isfull(&q)) printf("Overflow"); else { printf("Enter the element to add"); scanf("%d",&num); addq(&q,num); } break; case 2: if(isempty(&q)) printf("Underflow"); else { num=removeq(&q); printf("The removed element is %d", num); } break; } }while(choice!=3); return 0; }
OUTPUT :
1: ADD 2: REMOVE 3: EXIT Enter your choice 1 Enter the element to add 23 1: ADD 2: REMOVE 3: EXIT Enter your choice 1 Enter the element to add 42 1: ADD 2: REMOVE 3: EXIT Enter your choice 2 The removed element is 23 1: ADD 2: REMOVE 3: EXIT Enter your choice 2 The removed element is 42 1: ADD 2: REMOVE 3: EXIT Enter your choice 2 Underflow 1: ADD 2: REMOVE 3: EXIT
1 Comments
Thanks for sharing this
ReplyDeleteThanks,To visit this blog.