C program for insertion and deletion in Linear Queue

Mr Coder February 15, 2013 1




 C program for insertion and deletion in Linear Queue : A linear queue models the FIFO(first in first out) data structure, much like a line in real life. The first person in line will be the first person served, in queues the first element to be added is the first that can be removed. The only adding point is to the end of the list and the only removal point is the beginning of the list.

C program for insertion and deletion in Linear Queue :

#include<stdio.h> 
#include<conio.h> 
#include<stdlib.h> 
#define MAX 50 
typedef enum{true,false} bool; 
typedef struct{ 
int front,rear; 
int elements[MAX]; 
}queue; 
bool isfull(queue *); 
bool isempty(queue *); 
void create(queue *); 
void enqueue(queue *,int); 
void dequeue(queue *); 
void peek(queue *); 
void trav(queue *); 
void main() 
{ 
int choice,element; 
queue *pq, q; 
create(&q);
while(1){ 
printf("\n1-enqueue\n2-dequeue\n3-peek\n4-traverse\n5-exit\n"); 
scanf("%d",&choice); 
switch(choice) 
{ 
case 1: 
if(isfull(&q)) { 
printf("queue full"); 
getch(); 
} 
else{ 
printf("enter the value"); 
scanf("%d",&element); 
enqueue(&q,element); 
} 
break; 
case 2:  
if(isempty(&q)) { 
printf("queue empty\nenter any key to continue"); 
getch(); 
} 
else { dequeue(&q); 
printf("\npress any key to continue"); 
getch(); 
} 
break; 
case 3: 
if(isempty(&q)) { 
printf("stack empty\nenter any key to continue"); 
getch(); 
} 
else { 
peek(&q); 
printf("\npress any key to continue"); 
getch(); 
} 
break; 
case 4:
trav(&q); 
printf("\npress any key to continue"); 
getch(); 
break; 
case 5:
exit(1); 
} 
} 
getch(); 
} 

void create(queue *pq) 
{ 
pq->front=pq->rear=-1; 
} 
bool isfull(queue *pq) 
{ 
if((pq->front==0)&&(pq->rear==MAX-1)) { 
return 1; } 
else {
return 0;} 
} 

bool isempty(queue *pq) 
{ 
if(pq->front==-1) 
return 1; 
else 
return 0; 
} 

void enqueue(queue *pq,int element) 
{int i; 
if(pq->front==-1) 
pq->front=pq->rear=0; 
else if (pq->rear==MAX-1) 
{ 
for(i=pq->front;i<=pq->rear;i++) 
pq->elements[i-pq->front]=pq->elements[i]; 
pq->rear=pq->rear+pq->front-1; 
pq->front=0; 
} 
else pq->rear++; 
pq->elements[pq->rear]=element; 

} 

void dequeue(queue *pq) 
{ 
int temp; 
temp=pq->elements[pq->front]; 
if(pq->front==pq->rear) pq->front=pq->rear=-1; 
else pq->front++; 
printf("deleted val is %d",temp); 
} 

void peek(queue *pq) 
{ 
printf("front element is %d",pq->elements[pq->front]); 
} 

void trav(queue *pq) 
{ 
int i; 
for(i=pq->front;i<=pq->rear;i++) 
printf("%d\t",pq->elements[i]); 
}

 I hope you all have understood the code. If you have any doubts or queries regarding the code ask us in form of comments.

 

One Comment »

  1. Get Back March 4, 2013 at 2:39 pm - Reply

    Great write-up, Iˇm normal visitor of oneˇs web site, maintain up the excellent operate, and It’s going to be a regular visitor for a long time.

Leave A Response »