11.Write a C program using dynamic variables and pointers to construct a queue of integers using a singly linked list to perform the following operations:
a. Insert
b. Delete
c. Display
It must print appropriate messages for queue full and empty.
Program:
#include"stdio.h" /*PREPROCESSOR DIRECTIVES*/*/
#include"conio.h"
#include"alloc.h"
#define QSIZE 3 /*SYMBOLIC CONSTANTS*/
int count=0;
struct node /*STRUCTURE TEMPLATE DECLARATION*/
{
int data;
struct node *next;
};
typedef struct node *Node;
/*FUNCTION PROTOTYPE DECLARATION*/
Node insert_rear(int,Node);
Node delete_front(Node);
Node getnode();
void freenode(Node);
void display(Node);
void main()
{
int item,ch,choice; /*VARIABLE DECLARATION*/
Node first=NULL;
clrscr();
do{ /*DO-WHILE LOOP*/
printf("\n1:INSERT, 2:DELETE, 3:DISPLAY, 4:EXIT\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice) /*SWITCH STATEMENT*/
{
case 1:printf("Enter the item to be inserted\n");
scanf("%d",&item);
first=insert_rear(item,first);
break;
case 2:first=delete_front(first);
break;
case 3:display(first);
break;
case 4:exit(1);
break;
} /*END OF SWITCH STATEMENT*/
printf("Do you want to continue?(y/n):\n");
ch=getche();
}
while(ch!='n'); /*END OF DO-WHILE LOOP*/
getch();
}
/*FUNCTION TO ALLOCATE MEMORY DYNAMICALLY*/
Node getnode()
{
Node temp;
temp=(Node)malloc(sizeof(struct node));
return temp;
}
/*FUNCTION TO DEALLOCATE MEMORY OCCUPIED BY A NODE*/
void freenode(Node p)
{
free(p);
}
/*FUNCTION TO INSERT A NODE AT THE FRONT END*/
Node insert_rear(int item,Node first)
{
Node temp,cur;
temp=getnode();
if(count==QSIZE)
{
printf("Queue Full\n");
return first;
}
else
{
count++;
/*temp=getnode();*/
temp->data=item;
temp->next=NULL;
if(first==NULL)
return temp;
cur=first;
while(cur->next!=NULL)
cur=cur->next;
cur->next=temp;
return first;
}
}
/*FUNCTION TO DELETE A NODE FROM THE END*/
Node delete_front(Node first)
{
Node temp;
if(first==NULL)
{
printf("Queue is Empty\n");
}
else
{
count--;
temp=first;
first=first->next;
printf("Deleted data is %d\n",temp->data);
freenode(temp);
}
return first;
}
/*FUNCTION TO DISPLAY THE CONTENTS OF THE QUEUE*/
void display(Node first)
{
Node temp;
if(first==NULL)
{
printf("Queue is Empty\n");
}
else
{
printf("Queue status:\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
}
No comments:
Post a Comment