Saturday, February 6, 2010

Queueusing linked list

//TO IMPLEMENT QUEUES USING LINKED LISTS
# include
# include
#include


class lqueue
{
public:
struct queue
{
int data;
struct queue *next;
};
typedef struct queue node;
node *front, *rear;
lqueue()
{
front=rear=NULL;
}
void create();
void insert();
void dele();
void display();
};

void lqueue::create()
{
node *temp;
int item;
rear=new node;

cout<<"Enter element to be inserted: "; cin>>item;
rear->data=item;
rear->next=NULL;
front=rear;
display();
do
{
cout<<"\nEnter the element to be inserted and type -1 at end:"; cin>>item;

if(item!=-1)
{
temp=new node;
temp->data=item;
temp->next=NULL;
rear->next=temp;
rear=temp;
display();
}
}
while(item!=-1);

}




void lqueue::insert()
{
int item;
node *temp, *New;
temp=new node;
cout<<"\n Enter element to be inserted:"; cin>>item;
temp->data=item;
if(front==NULL)
{
temp->next=NULL;
front=rear=temp;
}
else
{
temp->next=NULL;
rear->next=temp;
rear=temp;
display();
}
}

void lqueue::dele()
{
node *temp=front;
if(front==NULL)
cout<<"\n Queue underflow"; else { cout<<"\n Deleted item is: " <data;
front=front->next;
delete temp;
}
display();
}
void lqueue::display()
{
node *temp;
temp=front;
cout<<"\n"; while(temp!=NULL) { cout<data<<"->\t";
temp=temp->next;
}
}

void main()
{
lqueue q1;
clrscr();
int ch;
q1.create();
q1.display();
while (ch!=4)
{
cout<<"\n 1. Insert \t 2. Delete \t 3. Display \t 4. Exit \n"; cout<<"Enter your choice:"; cin>>ch;
switch(ch)
{
case 1:q1.insert();
break;
case 2:q1.dele();
break;
case 3:q1.display();
break;
case 4:exit(0);
}
}

getch();
}