Tuesday, 3 November 2015

CPP Program for Single linked list - Data Structures

#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *link;
};
node *slist=NULL;
void insBeg(int val)
{
node *newnode = new node;

newnode->data=val;
newnode->link=slist;
slist=newnode;
}
void insEnd(int val)
{

if(slist==NULL)
{
node *newnode = new node;
newnode->data=val;
newnode->link=NULL;
slist=newnode;
}
else
{
node *temp=slist;
while(temp->link!=NULL)
temp=temp->link;
node *newnode = new node;
newnode->data=val;
newnode->link=NULL;
temp->link=newnode;
}
}
int insLoc(int val,int loc)
{
node *temp=slist;

for(int i=1;i<loc;i++)
{
temp=temp->link;
if(temp==NULL)
{
cout<<"\nInvalid Location:";
return 0;
}
}
node *newnode=new node;
newnode->data=val;
newnode->link=temp->link;
temp->link=newnode;
}
int delnode(int val)
{
if(slist->link==NULL && slist->data == val)
slist=NULL;
node *temp=slist;
while(temp!=NULL)
{
node *p;
if(temp->data==val)
{
   if(temp==slist)
   slist=temp->link;
   else
   {
     p->link=temp->link;
    }
    delete temp;
     return 0;
}
else
{
p=temp;
temp=temp->link;
}
}
cout<<"\nData not found";
}

int retrive(int loc)
{
node *temp=slist;
int count=1;
while(temp!=NULL)
{
if(count==loc)
return temp->data;
temp=temp->link;
count++;
}
cout<<"Invalid location";
}
int countnode()
{
node *temp=slist;
int count=1;
while(temp->link!=NULL)
{
temp=temp->link;
count++;
}
return count;
}

void display()
{
node *temp=slist;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->link;
}
}

int main()
{
int choice,val,loc;
do
{
cout<<"\nSINGLE LINKED LIST\n1.Insert at the Beginning \n2.Insert at end\n3.Insert at location\n4.delete\n5.retrive\n6.Count\n7.Display\n8.Exit";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\nEnter the data:";cin>>val;
insBeg(val);
break;
case 2:
cout<<"\nEnter the data:";cin>>val;
insEnd(val);
break;
case 3:
cout<<"\nEnter the data,location:";cin>>val;cin>>loc;
insLoc(val,loc);
break;
case 4:
cout<<"\nEnter the data:";cin>>val;
delnode(val);
break;
case 5:
cout<<"\nEnter the location:";cin>>val;
cout<<"\nretrieved data:"<<retrive(val);
break;
case 6:
cout<<"\nNumber of nodes:";cout<<countnode();
break;
case 7:
display();
break;
case 8:
return 0;
break;
}


}while(1);
return 0;
}

No comments:

Post a Comment