#include<iostream.h>
#include<conio.h>
class node
{
public:
node *next;
int data;
public:
void
remove(int);
void sort();
void
display();
int count();
int
search(int);
void
add(int);
void insert(int,int);
};
node *p;
/* add function*/
void node::
add(int num)
{
node *q=p;
if(p==NULL)
{
p=new node;
p->data=num;
p->next=NULL;
}
else
{
while(q->next!=NULL)
{
q=q->next;
}
q->next=new
node;
q->next->data=num;
q->next->next=NULL;
}
}
/* insert function*/
void
node::insert(int pos,int num)
{
node *q=p;
node *temp;
int i;
if(pos==1)
{
p=new node;
p->data=num;
p->next=q;
}
if(pos==count()+1)
{
add(num);
}
for(i=1;i<=(pos-2);i++)
{
q=q->next;
}
temp=q->next;
q->next=new
node;
q->next->data=num;
q->next->next=temp;
}
/* display function*/
void
node::display()
{
node *q=p;
if(p==NULL)
{
cout<<"\nLinked
List does not exist";
}
else
{
cout<<"\n";
while(q!=NULL)
{
cout<<"\t"<<q->data;
q=q->next;
}
}
}
/* sort function*/
void
node::sort()
{
int temp;
node *i=p;
node *j;
for(i=p;i!=NULL;i=i->next)
{
for(j=i->next;j!=NULL;j=j->next)
{
if(i->data>j->data)
{
temp=i->data;
i->data=j->data;
j->data=temp;
}
}
}
cout<<"The
linked list has been sorted.";
}
/* count function*/
int
node::count()
{
int i=0;
node *q=p;
if(p==NULL)
return 0;
else
{
while(q!=NULL)
{
q=q->next;
i++;
}
return i;
}
}
/* search function*/
int
node::search(int num)
{
node *q=p;
int pos=1;
int flag=0;
while(q!=NULL)
{
if(q->data==num)
{
flag=1;
break;
}
pos++;
q=q->next;
}
if(flag==1)
{
return pos;
}
else
{
return -1;
}
}
/* remove function*/
void
node::remove(int pos)
{ node *q=p;
node *temp;
if(pos==1)
{
p=q->next;
delete q;
}
for(int
i=1;i<=(pos-2);i++)
{
q=q->next;
}
temp=q->next;
q->next=q->next->next;
delete temp;
}
/* main() function*/
void main()
{
clrscr();
p=NULL;
int num,option;
char ch;
node n;
ch='y';
while(ch=='y')
{
cout<<"\n1.ADD ";
cout<<"\t 2. DISPLAY
";
cout<<"3. SORT \n";
cout<<"4. COUNT ";
cout<<"5. SEARCH ";
cout<<"6. INSERT \n";
cout<<"7. REMOVE " ;
cout<<"\nEnter your choice :
\n";
cin>>option;
switch(option)
{
case 1:
{
cout<<"Enter the Number : ";
cin>>num;
n.add(num);
break;
}
case 2:
{
n.display();
break;
}
case 3:
{
n.sort();
break;
}
case 4:
{
num=n.count();
cout<<"\nThe Number of Nodes are
: "<<num;
break;
}
case 5:
{
cout<<"Enter the Number to
search : ";
cin>>num;
int temp;
temp=n.search(num);
if(temp==-1)
{
cout<<"\nThe Value is not
present in the linked List";
}
else
{
cout<<"The Number has been found
at position : \n"<<temp;
}
break;
}
case 6:
{
int
pos;
cout<<"\n\n Enter position:
";
cin>>pos;
int nn=0;
nn=n.count();
if(pos>=1 && pos<=(nn+1))
{
int num;
cout<<"\n Enter number to be
insert: ";
cin>>num;
n.insert(pos,num);
}
else
{
cout<<"\n invalid position";
}
break;
}
case 7:
{
int
pos;
cout<<"\n Enter position: ";
cin>>pos;
if(pos>=1 &&
pos<=(n.count()+1))
{
n.remove(pos);
}
else
{
cout<<"\n Invalid
position";
}
break;
}
default:
{
cout<<"Invalid
Selection";
}
}
cout<<"\n\n
Do you want to continue(y/n): ";
cin>>ch
;
}
}
No comments:
Post a Comment