Friday, October 19, 2007

4.queue using linked list

/*.........queue using linked list......... */
#include<iostream.h>
#include<conio.h>
#include<process.h>
int ele;
template<class t>
class queue
{
struct node
{ t info;
struct node *next;
};
typedef struct node node;
node *front, *rear;
node *create(){return new node;}
public: queue() { front=NULL; rear=NULL; }
void insert (t ele)
{
node *temp=create();
if(rear==NULL&&front==NULL)
{ temp->info=ele;
temp->next=rear;
rear=temp;
front=rear;
}
else
{ temp->info=ele;
temp->next=rear;
rear=temp;
}
cout<<"\nThe element inserted is"<<temp->info;
}
void del()
{
node *temp;
temp=rear;
if(front==NULL&&rear==NULL)
{
cout<<"underflow";
getch();
}
else
{ if (temp->next==NULL)
{ cout<<"\ndeleted element is "<<temp->info;
delete temp;
rear=NULL;
front=NULL;
}
else
{ node *t;
while(temp->next!=NULL)
{
t=temp;
temp=temp->next;
}
cout<<"\nthe deleted element is "<<temp->info;
delete temp;
t->next=NULL;
}
}
}
void display()
{
node *temp;
temp=rear;
if(front==NULL&&rear==NULL)
cout<<"Queue is empty...";
cout<<"\nthe elements:";
while(temp!=NULL)
{
cout<<"\t"<<temp->info; temp=temp->next;
}
}
};
void main()
{ queue<int>q;
int ch;
int ele;
while(1)
{clrscr();
cout<<"\nselect any choice\n 1.insert\n2.delete\n3.display\n4.exit"; cin>>ch;
switch(ch)
{
case 1: cout<<"enter element to insert"; cin>>ele;
q.insert(ele);
break;
case 2: q.del();
getch();
break;
case 3: q.display();
getch();
break;
case 4: exit(0);
}
}
getch();
}

No comments: