C++ PROGRAM FOR SINGLY LINKED LIST



#include<iostream.h>
#include<conio.h>
class slist
{
private:
struct node
{
node *link;
int data;
} *p;
public:
slist():p(NULL)
{
}
~slist();
void addbeg(int);
void addend(int);
void addafter(int,int);
void de(int);
void slistshow();
int slistcount();
};
void slist::addend(int n)
{
node *q,*t;
if(p==NULL)
{
p=new node;
p->link=NULL;
p->data=n;
}
else
{
q=p;
while(q->link!=NULL)
q=p->link;
t=new node;
t->data=n;
t->link=NULL;
q->link=t;
}
}
void slist::addbeg(int n)
{
node *q;
q=new node;
q->link=p;
q->data=n;
p=q;
}
void slist::addafter(int c,int n)
{
node *q,*t;
int i;
for(i=0,q=p;i<c;i++)
{
q=q->link;
if(q==NULL)
{
cout<<"there are less tham"<<c<<"elements"<<endl;
return;
}
}
t=new node;
t->data=n;
t->link=q->link;
q->link=t;
}
void slist::de(int n)
{
node *q,*r;
q=p;
if(q->data==n)
{
p=q->link;
delete q;
return;
}
r=q;
while(q!=NULL)
{
if(q->data==n)
{
r->link=q->link;
delete q;
return;
}
r=q;
q=q->link;
}
cout<<"element"<<n<<"not is the list"<<endl;
}
void slist::slistshow()
{
node *q;
for(q=p;q!=NULL;q=q->link)
cout<<q->data<<endl;
}
int slist::slistcount()
{
node *q;
int c=0;
for(q=p;q!=NULL;q=q->link)
c++;
return c;
}
slist::~slist()
{
node *q;
if(p==NULL)
return;
while(p!=NULL)
{
q=p->link;
delete p;
p=q;
}
}
void main()
{
slist t1;
int ch,item,after;
do
{
clrscr();
cout<<"*********SINGLY LINKED LIST*********\n";
cout<<"1.Add at beginning \n";
cout<<"2.Add at end \n";
cout<<"3.Add at after \n";
cout<<"4.Show list \n";
cout<<"6.cout list \n";
cout<<"7.quit \n";
cout<<"Enter your choice(1-7)";
cin>>ch;
switch(ch)
{
case 1:
cout<<"enter the node value:";
cin>>item;
t1.addbeg(item);
t1.slistshow();
break;
case 2:
cout<<"enter the node value:";
cin>>item;
t1.addend(item);
t1.slistshow();
break;
case 3:
cout<<"enter the node value:";
cin>>item;
cout<<"enter after which node....";
cin>>after;
t1.addafter(after-1,item);
t1.slistshow();
break;
case 4:
t1.slistshow();
break;
case 5:
item=t1.slistcount();
cout<<"total nodes in the list:"<<item<<endl;
break;
case 6:
cout<<"enter the node value to be detected:";
cin>>item;
t1.de(item);
t1.slistshow();
break;
case 7:
break;
}
cout<<"press any to continue....";
getch();
}
while(ch!=7);
}

OUTPUT:
*********SINGLY LINKED LIST*********
1.Add at beginning
2.Add at end
3.Add at after
4.Show list
6.cout list
7.quit
Enter your choice(1-7)
4
10
50
press any to continue....

No comments:

Post a Comment