1_Append
2_Add @ begin
3_Add @ Next Position
4_Delete
5_Display */
#include
#include
#include
struct node
{
int data;
struct node *link;
};
class linklist
{
node *p;
public:
linklist();
void append(int);
void add_at_beg(int);
void add_after(int,int);
void del(int);
void display();
int count();
~linklist();
} ;
linklist::linklist()
{
p=NULL;
}
void linklist::append(int num)
{
node *q,*t;
//checks if list is empty
if(p==NULL)
{
//insert first node
p=new node;
p->data=num;
p->link=NULL;
}
else
{
q=p;
while(q->link!=NULL)
{
q=q->link;
}
t=new node;
t->data=num;
t->link=NULL;
q->link=t;
}
}
void linklist::add_at_beg(int num)
{
node *t;
t=new node;
t->data=num;
t->link=p;
p=t;
}
//add a node after a specified number of node
void linklist::add_after(int num,int c)
{
node *q,*t;
q=p;
//skip to the desired position
for(int i=1;i
q=q->link;
//if end of linklist is encountered
if(q==NULL)
{
cout<<"There are less than "<
}
}
//insert new node
t=new node;
t->data=num;
t->link=q->link;
q->link=t;
}
//delete the specified node linklist
void linklist::del(int num)
{
node *q;
q=p;
//traverse linklist till the last but one node is reached
while(q!=NULL)
{
//if node to be deleted in front node
if(q->data==num)
{
p=q->link;
delete(q);
return;
}
q=q->link;
}
cout<<"Element "<
}
void linklist::display()
{
node *q;
cout<<"The linklist is\n";
for(q=p;q!=NULL;q=q->link)
cout<
}
int linklist::count()
{
node *q;
int count=0;
q=p;
while(q!=NULL)
{
count++;
q=q->link;
}
return(count);
}
linklist::~linklist()
{
node *q;
if(p==NULL)
return;
while(p!=NULL)
{
q=p->link;
delete(p);
p=q;
}
}
void main()
{
int c,ele,pos;
clrscr();
linklist l;
do
{
cout<<"\n------Link List operations---------";
cout<<"\n1_Append";
cout<<"\n2_Add at Beginning";
cout<<"\n3_Add at Next position:";
cout<<"\n4_Deletion";
cout<<"\n5_Count the linkedlist";
cout<<"\n6_Display Linkedlist";
cout<<"\n7_Exit";
cout<<"\nEnter choice<1-7>:";
cin>>c;
switch(c)
{
case 1:
cout<<"\nEnter the item to append:";
cin>>ele;
l.append(ele);
break;
case 2:
cout<<"\nEnter the item to insert at beginning:";
cin>>ele;
l.add_at_beg(ele);
break;
case 3:
cout<<"\nEnter the position to insert:";
cin>>pos;
cout<<"\nEnter the item to be inserted:";
cin>>ele;
l.add_after(ele,pos);
break;
case 4:
cout<<"\nEnter the item to delete:";
cin>>ele;
l.del(ele);
break;
case 5:
cout<<"\nThe number of nodes in linked list is "<
case 6:
l.display();
break;
case 7:
exit(0);
break;
default:
cout<<"\nInvalid choice!!!";
break;
}
}while(c!=7);
getch();
}
No comments:
Post a Comment