Menu Close

Double ended queue program in c

  • The following diagrams describe the way of inserting and deleting the elements into dequeue from front and rear.

Dequeue program:

#include<stdio.h>
#define SIZE 5
int deque[SIZE] , front=-1 , rear=-1 ;
void insertFront(int);
void insertRear(int);
void deleteFront(void);
void deleteRear(void);
void display(void);
int isOverflow(void);
int isUnderflow(void);
void main()
{
	int choice , ele ;
	while(1)
	{
		printf("/*Deque operations**/\n");
		printf("1.InsertFront\n");
		printf("2.InsertRear\n");
		printf("3.DeleteFront\n");
		printf("4.DeleteRear\n");
		printf("5.Display\n");
		printf("6.Quit\n");

		printf("Enter your choice : ");
		scanf("%d", &choice);
		
		if(choice==1 || choice==2)
		{
			printf("Enter element to insert : ");
			scanf("%d", &ele);
		}

		switch(choice)
		{
			case 1		:	insertFront(ele);
						break ;
			
			case 2		:	insertRear(ele);
						break ;
			
			case 3		:	deleteFront();
						break ;
			
			case 4		:	deleteRear();
						break ;
			
			case 5		:	display();
						break ;
			
			case 6		:	exit(1);
			defualt	:	printf("Invalid choice...\n\n");
		}
	}
}
void insertFront(int ele)
{
	if(isOverflow())
	{
		printf("Deque is Full \n\n");
	}
	else
	{
		if(front==-1)
		{
			front = rear = 0;
		}
		else if(front==0)
		{
			front = SIZE-1 ;
		}
		else
		{
			front--;
		}
		deque[front] = ele ;
	}
}
void insertRear(int ele)
{
	if(isOverflow())
	{
		printf("Deque is Full \n\n");
	}
	else
	{
		if(rear==-1)
		{
			front = rear = 0 ;
		}
		else if(rear==SIZE-1)
		{
			rear = 0 ;
		}
		else
		{
			rear++ ;
		}
		deque[rear] = ele ;
	}
}
void deleteFront(void)
{
	if(isUnderflow())
	{
		printf("Deque is Empty \n\n");
	}
	else
	{
		printf("Deleted : %d \n\n", deque[front]);
		if(front==rear)
		{
			front = rear = -1 ;
		}
		else if(front == SIZE-1)
		{
			front = 0 ;
		}
		else
		{
			front++ ;
		}
	}
}
void deleteRear(void)
{
	if(isUnderflow())
	{
		printf("Deque is Empty \n\n");
	}
	else
	{
		printf("Deleted : %d \n\n", deque[rear]);
		if(front==rear)
		{
			front = rear = -1 ;
		}
		else if(rear == 0)
		{
			rear = SIZE-1 ;
		}
		else
		{
			rear-- ;
		}
	}
}
void display()
{
	int i;
	if(front == -1)
	{
		printf("No elements to display\n\n");
	}
	else if(front<=rear)
	{
		for(i=front ; i<=rear ; i++)
		{
			printf("Element %d : %d \n", i+1, deque[i]);
		}
		printf("\n");
	}
	else
	{
		for(i=front ; i<=SIZE-1; i++)
		{
			printf("Element %d : %d \n",i+1,deque[i]);
		}
		for(i=0 ; i<=rear ; i++)
		{
			printf("Element %d : %d \n",i+1,deque[i]);
		}
		printf("\n");
	}
}
int isOverflow(void)
{
	if((front==rear+1) || (front==0 && rear==SIZE-1))
		return 1 ;
	else
		return 0 ;
}
int isUnderflow(void)
{
	if(front==-1 || rear==-1)
		return 1 ;
	else
		return 0 ;
}