Menu Close

dequeue program using pointers in c

Implementing DEQUE using pointers:

  • We represent the data using structure in this implementation.
  • We access elements using point to structure format.
  • Structure is an object; hence it is protected compare to regular implementation.
#include<stdio.h>
#include<process.h>
#define SIZE 6
 
typedef struct DoubleEndedQueue
{
	int data[SIZE];
	int rear,front;
}deque;

deque q ;
 
int isEmpty(deque *p);
int isFull(deque *p);
void insertRear(deque *p,int x);
void insertFront(deque *p,int x);
int deleteFront(deque *p);
int deleteRear(deque *p);
void print(deque *p);
 
void main()
{
	int i,x,ch,n;
	q.front=-1 ;
	q.rear=-1 ;
	while(1)
	{
		printf("\n1.Insert rear :");
		printf("\n2.Insert front :");
		printf("\n3.Delete rear :");
		printf("\n4.Delete front :");
		printf("\n5.Display :");
		printf("\n6.Exit\n");
		printf("\nEnter your choice :");
		scanf("%d",&ch);
		
		switch(ch)
		{
			case 1: printf("Enter element to insert : ");
					scanf("%d",&x);		
					if(isFull(&q))
						printf("Queue is isFull \n\n");
					else
						insertRear(&q,x);
					break;
							
			case 2: printf("Enter element to insert :");
					scanf("%d",&x);		
					if(isFull(&q))
						printf("Queue is isFull\n\n");
					else					
						insertFront(&q,x);
					break;
							
			case 3: if(isEmpty(&q))
					printf("Queue is isEmpty\n\n");
					else
					{		
						x=deleteRear(&q);
						printf("Deleted item is : %d\n\n",x);
					}
					break;
					
			case 4: if(isEmpty(&q))
					printf("Queue is isEmpty\n\n");
					else
					{							
						x=deleteFront(&q);
						printf("Deleted item is : %d\n\n",x);
					}
					break;
							
			case 5:	print(&q);
					break;
			
			case 6: exit(1);
			
			default: printf("Invalid choice \n\n");
		}
	}
}
 
int isEmpty(deque *P)
{
	if(P->rear==-1)
		return(1);
	
	return(0);
}
 
int isFull(deque *P)
{
	if((P->rear+1)%SIZE==P->front)
		return(1);
	
	return(0);
}
 
void insertRear(deque *P,int x)
{
	if(isEmpty(P))
	{
		P->rear=0;
		P->front=0;
		P->data[0]=x;
	}
	else
	{
		P->rear=(P->rear+1)%SIZE;
		P->data[P->rear]=x;
	}
}
 
void insertFront(deque *P,int x)
{
	if(isEmpty(P))
	{
		P->rear=0;
		P->front=0;
		P->data[0]=x;
	}
	else
	{
		P->front=(P->front-1+SIZE)%SIZE;
		P->data[P->front]=x;
	}
}

int deleteFront(deque *P)
{
	int x;
	x=P->data[P->front];
	if(P->rear==P->front)
	{
		P->front=-1;
		P->rear=-1;
	}
	else
	{
		P->front=(P->front+1)%SIZE;
	}
	
	return(x);
}
 
int deleteRear(deque *P)
{
	int x;
	x=P->data[P->rear];
	if(P->rear==P->front)
	{
		P->front=-1;
		P->rear=-1;
	}
	else
	{
		P->rear=(P->rear-1+SIZE)%SIZE;
	}
	return(x);
}
 
void print(deque *P)
{
	int i;
	if(isEmpty(P))
	{
		printf("\nQueue is isEmpty!!");
		exit(0);
	}
	i=P->front;
	while(i!=P->rear)
	{
		printf("\n%d",P->data[i]);
		i=(i+1)%SIZE;
	}
	printf("\n%d\n",P->data[P->rear]);
}