In: Computer Science
Write a C program to implement a queue (FIFO) of characters in a one-way, circular, linked list. One way means that each node has only one pointer, Q, (not both a rear and a front pointer), so the program must use pointers-to-pointers. Include functions to insert(), remove(), for use in main() where the user is prompted "Enter "i" to insert a new element, "r" to remove an element, "q" to quit:"
code
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
}*rear=NULL;
void insert(int item);
int del();
void display();
int isEmpty();
int peek();
int main()
{
int item;
char choice;
while(1)
{
printf("\n1.Enter i to insert\n");
printf("2.Enter r to Delete\n");
printf("4.Enter d to display \n");
printf("5.Enter q to Quit\n");
printf("\nEnter your choice : ");
scanf("%c",&choice);
switch(choice)
{
case 'i':
printf("\nEnter the element for insertion : ");
scanf("%d",&item);
insert(item);
break;
case 'r':
printf("\nDeleted element is %d\n",del());
break;
case 'd':
display();
break;
case 'q':
exit('q');
break;
}
}
}
void insert(int item)
{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=item;
if(tmp==NULL)
{
printf("\nMemory not available\n");
return;
}
if( isEmpty() ) /*If queue is empty */
{
rear=tmp;
tmp->link=rear;
}
else
{
tmp->link=rear->link;
rear->link=tmp;
rear=tmp;
}
}
del()
{
int item;
struct node *tmp;
if( isEmpty() )
{
printf("\nQueue underflow\n");
exit(1);
}
if(rear->link==rear)
{
tmp=rear;
rear=NULL;
}
else
{
tmp=rear->link;
rear->link=rear->link->link;
}
item=tmp->info;
free(tmp);
return item;
}
int isEmpty()
{
if( rear == NULL )
return 1;
else
return 0;
}
void display()
{
struct node *p;
if(isEmpty())
{
printf("\nQueue is empty\n");
return;
}
printf("\nQueue is :\n");
p=rear->link;
do
{
printf("%d ",p->info);
p=p->link;
}while(p!=rear->link);
printf("\n");
}
code
(SS)
output(SS)