Example – Single LinkedList
#include <iostream.h>
class List
{
private:
int
n;
List
*next,*head,*ptr;
public:
List()
{
next=head=ptr=NULL;
}
void
Add();
void
Disp();
void
Del();
void
Ins();
void
Reverse();
};
void
List::Add()
{
List
*temp;
temp=new
List();
cout<<"\n\tEnter
Data : ";
cin>>temp->n;
temp->next=NULL;
if(head==NULL)
{
ptr=head=temp;
}
else
{
ptr->next=temp;
ptr=temp;
}
}
void List::Disp()
{
List *pr;
cout<<"\n\tList ..
";
for(pr=head;pr;pr=pr->next)
{
cout<<pr->n<<"
";
}
}
void List::Del()
{
List *pr,*pr1;
int num;
cout<<"\n\tEnter
No. to Delete ";
cin>>num;
for(pr=head;pr;pr=pr->next)
{
if(pr->n==num)
{
break;
}
pr1=pr;
}
if(pr==head)
{
head=head->next;
}
else
if(pr==NULL)
{
cout<<"\n\tNumber not
Found!!\n";
}
else
{
pr1->next=pr->next;
}
delete(pr);
}
void List::Ins()
{
List *temp,*ptr1;
int num,pos,i=0;
cout<<"\n\tEnter
Number to Add : ";
cin>>num;
cout<<"\n\tEnter
Position : " ;
cin>>pos;
temp=new
List();
temp->next=NULL;
temp->n=num;
for(ptr1=head;ptr1->next!=NULL;ptr1=ptr1->next)
{
i++;
if(i==pos)
{
break;
}
}
if(ptr1==head)
{
temp->next=head;
head=temp;
}
else
if(ptr1->next==NULL)
{
ptr1->next=temp;
}
else
{
temp->next=ptr1->next;
ptr1->next=temp;
}
}
void
List::Reverse()
{
List
*ptr1,*ptr2,*ptr3;
ptr1=head;
ptr2=NULL;
while(ptr1!=NULL)
{
ptr3=ptr2;
ptr2=ptr1;
ptr1=ptr1->next;
ptr2->next=ptr3;
}
head=ptr2;
}
int
main()
{
int
ch=0;
List
L;
while(ch<6)
{
cout<<"\n\t1.
Add ";
cout<<"\n\t2.
Display";
cout<<"\n\t3.
Delete";
cout<<"\n\t4.
Insert ";
cout<<"\n\t5.
Reverse";
cout<<"\n\t6.
Exit ";
cout<<"\n\tEnter a Choice
";
cin>>ch;
switch(ch)
{
case
1:L.Add();break;
case
2:L.Disp();break;
case
3:L.Del();break;
case
4:L.Ins();break;
case
5:L.Reverse();break;
case
6:cout<<"\n\t\tBye ....";break;
default:cout<<"\n\t\tInvalid
Choice ";
}
}
return
0;
}
No comments:
Post a Comment