C Programming language

adplus-dvertising
C - Queue Dynamic implementation
Previous Home Next

Dynamic Implementation of the queue is generally done by using the pointers, infact we will be using a linked list for creating and storing elements in a queue. Linked List implementation allows better memory utilization, and we can increase and decrease the size of the queue as per our requirement.

As we know that the dynamic implementation is achieved through pointers using the linked list. The following is a code  snippet that illustrates how we can dynamically implement the queue using linked lists. In this approach we take the first element of list as front and last element of the as the rear of the queue.

#include <stdio.h>
#include<conio.h>
#define<stdlib.h>
void enqueue();
void dequeue();
void display();
struct queue
{
 int num;
 struct queue *next;
};
typedef struct queue Q;
Q *head==NULL;
Q *temp, *first;
void main()
{
int choice;
char ch;
clrscr();
printf("Program for various operations on Queue using linked list");
do
{
 printf("\n1. Enqueue");
 printf("\n2. Dequeue");
 printf("\n3. Display");
 printf("Enter your choice :");
 scanf("%d",&choice);
 switch(choice)
{
     case 1: enqueue();
         break;
     case 2: dequeue();
         break;
     case 3: display();
         break;
 default : printf("\nwrong choice made");
    }
printf("\ndo you want to continue y/n");
fflush(stdin);
scanf("%c",&ch);
}
while ((char=='y')||(char=='Y'));
getch();
}
void enqueue()
{
int info;
temp=(Q *)malloc(sizeof(stck));
printf("\nEnter the element in the  Queue :");
scanf("%d",&info);
temp->num=info;
temp->next=NULL
if(head==NULL)
{
    printf("\nQueue is empty");
head=temp;
}
else
{
     first=head;
 while(first!=NULL)
 first=first->next;
 first->next=temp;
    }
}
void dequeue()
{
if(head==NULL)
{
     printf("\n the stack is empty");
}
else
{
     temp=head;
 head=head->next;
 free(temp);
 }
}
void display()
{
 int i;
 if(head==NULL)
 printf("\n stack is empty");
 else
{
     temp=head;
 printf("\nThe status of the stack is :");
 while(temp!=NULL)
{
     printf("%d",temp->num);
    }
}
}
Previous Home Next