PROGRAM CODING:-
#include<stdio.h> //header files
#include<stdlib.h>
struct queue //queue structure
{
int data;
struct queue *next;
};
void initqueue(struct queue *head) //initialising head to NULL
{
head->next=NULL;
}
int isempty(struct queue *head) //checks whether queue is empty
{
return (head->next==NULL);
}
void enqueue(struct queue *head,int data) //enqueue function
{
struct queue *newnode,*q,*temp;
q=temp=head;
newnode=(struct queue *)malloc(sizeof(struct queue));
newnode->data=data;
if(q->next==NULL) //cir q:if queue is empty,make a new node to hold the data and make the node point back to itself
{
q->next=newnode;
newnode->next=q;
}
else
{
while(q->next!=temp) //traversing to last
q=q->next;
newnode->next=q->next; //make the new node point the first node
q->next=newnode; //make the last node to point the new node
}
}
int dequeue(struct queue *head)
{
struct queue *temp,*q=head->next;
int data;
if(isempty(head))
{printf("Queue is empty!**!");return -1;}
else
{
data=head->next->data;
temp=(struct queue *)malloc(sizeof(struct queue));
temp=head->next;
while(head->next!=q)
head=head->next;
head->next=head->next->next; //skipping the node to be dequeued
if(head->next->next==head->next) //if there is only one node in the queue reinitialise the queue
initqueue(head);
free(temp); //free the dequeued node
}
return data;
}
void makeempty(struct queue *head)
{
struct queue *temp=head;
if(isempty(head))
printf("Queue is already empty!**!");
else
{
while(head->next!=temp)
dequeue(head);
printf("Queue made empty!**!");
}
}
void display(struct queue *head)
{
struct queue *temp=head;
if(isempty(head))
printf("Queue is empty!**!");
else
{
printf("Contents of the queue are:\n");
while(head->next!=temp)
{
printf("%d\t",head->next->data);
head=head->next;
}
}
}
int count(struct queue *head)
{
struct queue *temp=head;
int c=0;
if(isempty(head))
{printf("Queue is empty!**!");return -1;}
else
{
while(head->next!=temp)
{
head=head->next;
c++;
}
return c;
}
}
void deletequeue(struct queue *head)
{
makeempty(head);
free(head);
}
int main()
{
int ch,data;
struct queue *head;
head=(struct queue *)malloc(sizeof(struct queue));
initqueue(head);
while(1)
{
printf("\nQUEUE MENU:\n\t1.Enqueue\n\t2.Dequeue\n\t3.Display\n\t4.Count\n\t5.Make empty\n\t6.Delete Queue and Exit\nChoice:");
scanf("%d",&ch);
if(ch==6)
break;
switch(ch)
{
case 1:
printf("Enter the data to be enqueued: ");
scanf("%d",&data);
enqueue(head,data);
display(head);
break;
case 2:
data=dequeue(head);
if(data!=-1)
printf("Element dequeued: %d",data);
break;
case 3:
display(head);
break;
case 4:
data=count(head);
if(data!=-1)
printf("Count: %d",data);
break;
case 5:
makeempty(head);
break;
case 6:
deletequeue(head);
return 1;
default:printf("Enter correct menu option!**!");
}
}
return 0;
}
No comments:
Post a Comment