Wednesday, September 29, 2010

(OOPS)Implementation of linked list using template

EX NO.            IMPLEMENTATION OF LINKED LIST USING TEMPLATES


 AIM:To write a c++ program to implement the linked list using templates.

 ALGORITHM:
Step 1: Start the program.
Step 2: Create and declare the template class.
Step 3:To create,insert,delete,search and display the elements of linked list corresponding functions are created and called respectively.
Step 4:Define the main function
Step 5:Stop the program.


PROGRAM:
 #include<iostream.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
template<class T>
class list
{
T item;
public:
struct node
{
 T data;
 struct node*next;
 };
 struct node*start,*p,*new1[25];
 void create();
 void insert();
 void delete1();
 void search();
 void display();
 };
 int pos,num,n,i,j;
 template<class T>
 void list<T>::create()
 {
 cout<<"\nenter the size";
 cin>>n;
 for(i=0;i<n;i++)
 {
 new1[i]=(struct node*)malloc(sizeof(struct node));
 cout<<"enter the data";
 cin>>item;
 new1[i]->data=item;
 new1[i]->next=NULL;
 if(i==0)
 {
 p=new1[i];
 start=new1[i];
 }
else
{
p->next=new1[i];
p=new1[i];
}
}
}
template<class T>
void list<T>::insert()
{
p=start;
cout<<"enter the pos";
cin>>pos;
new1[pos]=(struct node*)malloc(sizeof(struct node));
cout<<"enter the data";
cin>>item;
new1[pos]->data=item;
new1[pos]->next=NULL;
for(i=1;i<pos;i++)
{
p=p->next;
}
new1[pos]->next=p->next;
p->next=new1[pos];
n=n+1;
}
template<class T>
void list<T>::delete1()
{
p=start;
cout<<"enter the position to be deleted";
cin>>pos;
for(i=0;i<pos-1;i++)
{
p=p->next;
}
p->next=p->next->next;
cout<<endl<<"node deleted";
n-=1;
}
template<class T>
void list<T>::search()
{
p=start;
pos=0;
cout<<"enterthe element to be search";
cin>>num;
for(i=0;i<=n;i++)
{
if(p->data==num)
{
pos=i;
cout<<"element found at"<<pos<<"pos";
break;
}
else
{
p=p->next;
}
}
if(pos==0)
cout<<"\nelement not found";
}
template<class T>
void list<T>::display()
{
p=start;
for(i=1;i<=n;i++)
{
cout<<p->data<<"->";
p=p->next;
}
cout<<"NULL";
}
void main()
{
int c;
clrscr();
list<int>lis;
for(;;)
{
cout<<"\nmenu...\n1.create\n2.insert\n3.delete\n4.search\n5.display\n6.exit";
cout<<"\nenter the choice";
cin>>c;
switch(c)
{
case 1:
lis.create();
break;
case 2:
lis.insert();
break;
case 3:
lis.delete1();
break;
case 4:
lis.search();
break;
case 5:
lis.display();
break;
case 6:
exit(0);
break;
default:
cout<<"\nenter the correct choice";
}
}
}

RESULT:
              Thus the program to implement linked list using templates is executed and the output is verified.