Friday, 15 December 2017

Write C++ programs to implement the Double Ended Queue (DEQUE) using array.

Implementation of above problem using C++:
#include <iostream>
using namespace std;
#define MAX 10
int front=-1,rear=-1,c,i;
template<class t>
class dqueADT
{
public:
virtual void addqatbeg()=0;
virtual void addqatend()=0;
virtual void delqatbeg()=0;
virtual void delqatend()=0;
virtual void display()=0;
};
template <class t>
class dque: public dqueADT<t>
{
public:
t q[MAX],item;
dque()
{
front=rear=-1;
for(i=0;i<MAX;i++)
q[i]=0;
}
void addqatbeg()
{
cout<<"Enter an element:";
cin>>item;
if (front==0&&rear==MAX-1)
{
cout<<"\nDeque is full"<<endl;
return ;
}
if(front==-1)
{
front=rear=0;
q[front]=item;
return;
}
if(rear!=MAX-1)
{
c=count();
int k=rear+1;
for(i=1;i<=c;i++)
{
q[k]=q[k-1];
k--;
}
q[k]=item;
front=k;
rear++;
}
else
{
front--;
q[front]=item;
}
}
void addqatend()
{
cout<<"Enter an element:";
cin>>item;
if(front==0&&rear==MAX-1)
{
cout<<"\nDeque is full"<<endl;
return;
}
if(front==-1)
{
rear=front=0;
q[rear]=item;
return;
}
if(rear==MAX-1)
{
int k=front-1;
for(i=front-1;i<rear;i++)
{
k=i;
if(k==MAX-1)
q[k]=0;
else
q[k]=q[i+1];
}
rear--;
front--;
}
rear++;
q[rear]=item;
}
void delqatbeg()
{
if(front==-1)
{
cout<<"\nDeque is empty"<<endl;
return;
}
item=q[front];
q[front]=0;
if(front==rear)
front=rear=-1;
else
front++;
cout<<"Deleted item is:"<<item;
}
void delqatend()
{
if(front==-1)
{
cout<<"\nDeque is empty"<<endl;
return;
}
item=q[rear];
q[rear]=0;
rear--;
if(rear==-1)
front=-1;
cout<<"Deleted item is: "<<item;
}
void display()
{
cout<<endl<<"front-> ";
for(i=0;i<MAX;i++)
cout<<" "<<q[i];
cout<<" <-rear";
}
int count()
{
int c=0;
for(i=0;i<MAX;i++)
{
if(q[i]!=0)
c++;
}
return c;
}
};
main()
{
int ch;
dque<int> s1;
do
{
cout<<"\n****Menu****";
cout<<"\n1. Insert at Beginning\n2. Insert at End\n3. Delete from Beginning\n4. Delete from End\n5. Display\n6. Exit";
cout<<"\nEnter ur choice:";
cin>>ch;
switch(ch)
{
case 1: s1.addqatbeg();
break;
case 2: s1.addqatend();
break;
case 3: s1.delqatbeg();
break;
case 4: s1.delqatend();
break;
case 5: s1.display();
break;
case 6: exit(1);
}
}
while(1);
return 0;
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput