Monday, July 21, 2008

Single Linked Lists

Hi All,

Many people know about Data Structures. In that Linked Lists and Trees will be the crucial concepts.... I know most of u people know this... but Here iam posting this for those who are not able to write code....





#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>

class S_List
{
float info;
S_List *link;
S_List *first;
public :
S_List()
{
first= NULL;
}
void Create();
void Insert();
void Delete();
void Display();
};⁄⁄end of S_List class

void S_List :: Create()
{
char ch;
S_List *temp;

first=NULL;
temp = new(S_List);

do
{
if(first==NULL)
first = temp;

cout<<"\n Enter Information :: ";
cin>>temp->info;

cout<<"Do You Want To Insert Another Element (Y⁄N) :: ";
cin>>ch;
if(ch=='Y'||ch=='y')
{
temp->link = new(S_List);
temp = temp->link;
}
else
temp->link=NULL;
}while(ch=='Y'||ch=='y');
}⁄⁄end of Create

void S_List :: Insert()
{
int pos,i;
S_List *temp,*New,*pre;

New = new(S_List);

if(first==NULL)
{
cout<<"\n The List Is Not Created...";
getch();
return;
}

cout<<"Enter Information :: ";
cin>>New->info;
cout<<"Enter Position :: ";
cin>>pos;

if(pos==1)
{
New->link = first;
first = New;
}⁄⁄end of if
else
{
i=1;
temp = first;
while(temp!=NULL && i<pos)
{
pre = temp;
temp = temp->link;
i++;
}⁄⁄end of While
if(pos>i)
{
cout<<"\n The Position Exceeds The List Size ...";
getch();
return;
}
else
if(temp==NULL&&pos==i)
{
New->link = NULL;
pre->link = New;
}
else
{
New->link=pre->link;
pre->link=New;
}⁄⁄end of else
}⁄⁄end of else
cout<<"\n The Value Inserted At "<<pos<<" Position";
getch();
}⁄⁄end of Insert

void S_List :: Delete()
{
int pos;
float key;
S_List *temp,*pre;

if(first==NULL)
{
cout<<"\n There Is No List Created to Delete Any Element...";
getch();
return;
}

cout<<"\n Enter Key Element To Delete :: ";
cin>>key;

temp = pre = first;
pos=1;

while(temp!=NULL && temp->info!=key)
{
pre = temp;
temp = temp->link;
pos++;
}⁄⁄end of While

if(temp->info==key)
{
if(pos!=1)
{
pre->link = temp->link;
delete(temp);
}
else
{
first = first->link;
delete(temp);
}
cout<<"The Key Element Deleted at "<<pos<<" Position...";
}
else
cout<<"The Key Element Is Not Exist in the List....";
getch();
}⁄⁄end of Delete

void S_List :: Display()
{
S_List *temp;
temp = first;

if(temp==NULL)
{
cout<<"\n\n *** The List Is Empty *** ";
getch();
return;
}

cout<<"\n\n The List Is :: ";
while(temp!=NULL)
{
cout<<" "<<temp->info;
temp = temp->link;
}
getch();
}⁄⁄end of Display

void main()
{
int ch;
S_List obj;

while(1)
{
clrscr();
cout<<" 1.CREATE \n";
cout<<" 2.INSERT \n";
cout<<" 3.DELETE \n";
cout<<" 4.DISPLAY \n";
cout<<" 5.EXIT \n";
cout<<"Choice :: ";
cin>>ch;
switch(ch)
{
case 1 : obj.Create(); break;
case 2 : obj.Insert(); break;
case 3 : obj.Delete(); break;
case 4 : obj.Display(); break;
case 5 : exit(0);
default : cout<<"\n Invalid Choice"; getch();
}⁄⁄end of switch
}⁄⁄end of while
}⁄⁄end of main()

No comments: