Linear Queue
Algorithm:Linear Queue Operations Let us consider a linear queue,Q with front side and rear side. Element will be inserted in rear side and will be deleted from front side.This algorithm helps us to perform insertion and deletion operation in the queue,Q. Initially, front=rear=-1; Qinsert(Q[1..N),front,rear,item) { if(rear=N-1) //checks if the Queue is full { print "Queue full" } else { rear=rear+1 //rear is incremented by 1 Q[rear]=item //element is inserted in rear side if(front=-1) { front=0 } } } Qdelete(Q[1..N),front,rear) { if(front=-1 and rear=-1) //checks if the Queue is empty { print "Queue empty" } else { item=Q[front] if(front=rear) //if front and rear is equal then they { both are initialized to -1 front=-1 rear=-1 } else { front=front+1 //front is incremented and the element }in front is deleted } return item } show(Q[1..N),front,rear) { if(front=-1 and rear=-1) //checks if the Queue is empty { print "Queue empty" } else { for(i=front to rear) { print "Q[i]" //elements are printed one by one from } front to rear } } C Program For Linear Queue Source Code: #include<tdio.h> #include<stdlib.h> int Q[5],f=-1,r=-1; void Qinsert(int item) { if(f==4) { printf("\nQueue full."); } else { r=r+1; Q[r]=item; if(f==-1) { f=0; } } } int Qdelete() { int item; if(f==-1) { printf("\nQueue empty."); } else { item=Q[f]; if(f==r) { f=-1; r=-1; } else { f=f+1; } } return item; } void show() { int i=0; printf("\nThe elements of the Queue are:"); for(i=0;i<=4;i++) { if(i>=f && i<=r) printf("\t%d",Q[i]); else printf("\t_"); } printf("\n"); } void main() { int ch,item; while(1) { printf("\n1.Qinsert 2.Qdelete 3.Show 4.Exit"); printf("\nEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter item:"); scanf("%d",&item); Qinsert(item); break; case 2: item=Qdelete(); printf("\nThe popped item is-> %d",item); break; case 3: show(); break; case 4: exit(0); } } } OUTPUT: 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:1 Enter item:11 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:1 Enter item:22 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:1 Enter item:33 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:1 Enter item:44 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:3 The elements of the Queue are: 11 22 33 44 _ 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:2 The popped item is-> 11 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:2 The popped item is-> 22 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:3 The elements of the Queue are: _ _ 33 44 _ 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:2 The popped item is-> 33 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:2 The popped item is-> 44 1.Qinsert 2.Qdelete 3.Show 4.Exit Enter your choice:2 Queue empty.
Tags:
Stack & Queue
0 comments