Menu Close

Dynamic Queue in C

Implementing dynamic queue using arrays:

  • Static queue is fixed in size.
  • After inserting size elements, it says “Queue is Full”.
  • We can create a Queue dynamically.
  • Stdlib.h header file functionality is used to implement dynamic queue
  • Initially we construct an array with specified size using calloc() function.
  • Dynamic queue has specific size.
  • Realloc() function can resize the array which is created using by calloc().

Create Queue:

void create()
{
	queue = (int*)calloc(n,sizeof(int));
	if(queue==NULL)
	{
		printf("Out of memory\n");
		exit(1);
	}
	else
	{
		front = rear = queue;
		printf("Queue is ready \n");		
	}
}

Insertion:

Deletion:

Implementation:

#include<stdio.h>
#include<stdlib.h>

int *queue , *front , *rear;
int n=5;

void create();
void insert();
void delete();
void display();

int main()
{
	int ch;
	create();	
	
	while(1)
	{
		printf("1. Insert \n");
		printf("2. Delete \n");
		printf("3. Display \n");
		printf("4. Quit \n");
		
		printf("Enter your choice : \n");
		scanf("%d", &ch);
		
		switch(ch)
		{
			case 1 : insert();
					 break;
		 
		 	case 2 : delete();
		 			 break;
			
			case 3 : display();
					 break;
			
			case 4 : exit(1);
			
			default : printf("Invalid choice \n\n");
		}
	}
}
void create()
{
	queue = (int*)calloc(n,sizeof(int));
	if(queue==NULL)
	{
		printf("Out of memory\n");
		exit(1);
	}
	else
	{
		front = rear = queue;
		printf("Queue is ready \n");		
	}
}

void insert()
{
	int ele;
	printf("Enter element : ");
	scanf("%d" , &ele);
	if(rear == front+n)
	{
		++n;
		queue = (int*)realloc(queue, n*sizeof(int));
		*rear++ = ele;
		printf("Element inserted \n");
	}
	else
	{
		*rear++ = ele;
		printf("Element inserted \n");
	}
}

void delete()
{
	if(front==rear)
	{
		printf("Queue is empty \n");
	}
	else
	{
		int *i;
		printf("Deleted : %d\n", *front);
		for(i=front+1 ; i<rear ; i++)
		{
			*(i-1) = *i;
		}
		rear--;
		if(n>5)
		{
			--n;
			queue = (int*)realloc(queue, n*sizeof(int));
		}
	}
}

void display()
{
	if(front==rear)
	{
		printf("Queue is empty\n");
	}
	else
	{
		int *i;
		printf("Queue elements are : \n");
		for(i=front ; i<rear ; i++)
		{
			printf("%d\n", *i);
		}
	}
}