Implement queue using linkedlist C++
/*
Queue as a linked list*/
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class
queue
{
private:
struct node
{ int data;
node
*link;
}*front,*rear;
public:
queue();
void
addq(int item);
int
delq();
void
display();
int
count();
};
queue::queue()
{ front=rear=NULL;}
void
queue::addq(int item)
{ node *temp;
temp=new
node;
if(temp==NULL)
cout<<"\n
Queue is full. ";
temp->data=item;
temp->link=NULL;
if(front==NULL)
{
rear=front=temp;
return;
}
rear->link=temp;
rear=rear->link;
}
int
queue::delq()
{ if(front==NULL)
{
cout<<"\n Queue is
empty. ";
return
NULL;
}
node
*temp;
int
item;
item=front->data;
temp=front;
front=front->link;
delete
temp;
return
item;
}
void
queue::display()
{ node *temp;
cout<<"(Front)
";
for(temp=front;temp!=NULL;temp=temp->link)
cout<<temp->data<<"
";
cout<<"(Rear)
";
}
int
queue::count()
{ int count=0;
node
*temp;
for(temp=front;temp!=NULL;temp=temp->link)
count++;
return
count;
}
void
main()
{ int c,num;
char
ch;
queue
q;
while(1)
{
clrscr();
cout<<"\n
Perform the following Queue operations. ";
cout<<"\n
--------------------------------------. ";
cout<<"\n
1.Insert Elements. ";
cout<<"\n
2.Delete Elements. ";
cout<<"\n
3.Display full Queue content. ";
cout<<"\n
4.Exit from the program. ";
do
{ cout<<"\n Select Your
Choice(1:4) : ";
cin>>c;
}
while((c<1)||(c>4));
clrscr();
switch(c)
{
case 1 :
do
{ cout<<"\n Queue currently has
"<<q.count()<<" elements. ";
cout<<"\n
Enter the new element : ";
cin>>num;
q.addq(num);
cout<<"\n
Add more (y/n) : ";
cin>>ch;
}
while((ch=='y')||(ch=='Y'));
break;
case
2 :
int num;
do
{ cout<<"\n Queue currently has
"<<q.count()<<" elements .";
if((num=q.delq())!=NULL)
cout<<"\n
The deleted element is : "<<num;
cout<<"\n
Current Queue is ";
q.display();
cout<<"\n
Delete More(y/n) : ";
cin>>ch;
}
while((ch=='y')||(ch=='Y'));
break;
case
3 :
cout<<"\n Queue currently has
"<<q.count()<<" elements as shown below ";
q.display();
break;
case
4 : exit(1);break;
}
cout<<"\n
Press Any Key to Continue....";
getch();
}
}
No comments:
Post a Comment