Monday, 25 August 2014

Singly Linked List

#include "stdafx.h"
#include<iostream>
using namespace std;
struct Link
{
int data;
Link *next;
};
class List
{
private:
Link *first;
public:
List()
{
first=NULL;
}
void set_values(int v)
{
Link *ptr,*temp;
if(first==NULL)
{
first=new Link;
first->data=v;
first->next=NULL;
}
else
{
ptr=first;
while(ptr->next!=NULL)
ptr=ptr->next;
temp=new Link;
temp->data=v;
temp->next=NULL;
ptr->next=temp;
}
}
void get_values()
{
Link *temp;
temp=first;
cout<<"Inserted Integers are..."<<endl;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
cout<<"\n\n";
}
void delete_values(int d)
{
Link *temp,*previous;
temp=first;
if(temp->data==d)
{
first=temp->next;
delete temp;
cout<<d<<" has been deleted from the List..."<<endl;
return;
}
previous=temp;
while(temp!=NULL)
{
if(temp->data==d)
{
previous->next=temp->next;
delete temp;
cout<<"Value deleted."<<endl;
return;
}
previous=temp;
temp=temp->next;
}
cout<<"\n"<<d<<" not found in the list."<<endl;
}

};
int main()
{
List s1;
int value,delet;
char choice;
do
{
cout<<"Do you want to add data in the List? (y/n)"<<endl;
cin>>choice;
if(choice=='y')
{
cout<<"Enter an Integer:"<<endl;
cin>>value;
s1.set_values(value);
}
else if(choice=='n')
{
cout<<"\nCongratulations!!!Data has been entered successfully!!!"<<endl;
cout<<"Thank you v.much!!!"<<endl;
}
else
{
cout<<"Invalid choice,,,Please try again!!!"<<endl;
}
}while(choice!='n');
cout<<"\n\nDo you wish to see the stored data?  (y/n)"<<endl;
cin>>choice;
if(choice=='y')
{
s1.get_values();
}
else
{
cout<<"\n\nThank you very much once again!!!"<<endl;
// exit(0);
}
do
{
cout<<"Do you want to delete the value from the list? (y/n)"<<endl;
cin>>choice;
if(choice=='y')
{
 cout<<"Enter a value to delete:"<<endl;
     cin>>delet;
     s1.delete_values(delet);
 cout<<"\nValues after deleting from the List!!!"<<endl;
 s1.get_values();
}
else
{
exit(0);
}
}
while(choice!='n');
return 0;
}

No comments:

Post a Comment