#include<iostream.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
class queue
{
struct node *front,*rear,*ptr;
public:
queue(){
rear=NULL;
front=NULL;
}
void enqueue(int);
void dqueue();
void display();
};
void queue::enqueue(int data)
{
ptr=new node;
if(rear==NULL)
{ front=ptr;
}
else
{
rear->link=ptr;
ptr->link=NULL;
}
rear=ptr;
rear->data=data;
cout<<"\n>>";
}
void queue::dqueue()
{
int item;
if(front==NULL)
cout<<"\nQueue is empty:\n";
else
{
item=front->data;
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
{
ptr=front;
front=front->link;
delete ptr;
}
cout<<"deleted elmnt : "<<item;
}
}
void queue::display()
{
ptr=front;
if(front==NULL)
cout<<"\nQueue is empty";
else
{
cout<<"\nElements in queue are: ";
while(ptr!=NULL)
{
cout<<ptr->data<<"|";
ptr=ptr->link;
}
}
}
void main()
{
queue q;
int ch,data;
clrscr();
cout<<"\n........MENU..........\n";
cout<<"1 . enqueue\n";
cout<<"2 . dqueue\n";
cout<<"3 . display\n";
cout<<"4 . exit\n";
while(1)
{
cout<<"\n Enter your choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n Enter the element: ";
cin>>data;
q.enqueue(data);break;
case 2:
q.dqueue();break;
case 3:
q.display();break;
case 4:
ch=5;break;
default:
cout<<"\nInvalid selection\n";break;
}
if(ch==5)
break;
}
getch();
}
Nice way to implement queues
ReplyDelete