Wednesday 12 October 2011

CREATING LINKED LIST USING TEMPLATES


CREATING LINKED LIST USING TEMPLATES
AIM:
To  write a program top perform various operations  in  a linked list using templates.

ALGORITHM:

Step1: Start the process.
Step2: Declare template class T and include the necessary header files.
Step3: Create a class for linked list node.
Step4: Declare the necessary member function, insert, display ,quit.
Step5: Initialize the head node to NULL.
Step6: Adding values to the tail or end of the list.
a.       check the head node for NULL. If it is null then new node will be assigned  to       head node .And the given input is given to the head node.
b.      If it is not null, a new node will be  created, while the new link node  is not equal to null then new value will be appeared to the new node.
Step7: Display the list.
            a. print the nodes if the node is not null.
Step 9: Inside main, call and invoke the function and pass the different data types.
Step 10:Display the results.
Step 11:Stop the process.

PROGRAM:

#include<iostream.h>
#include<conio.h>
#include<process.h>
template<class T>
class list
{
 private:
    int data;
     list *next;

 public:
   list()
   {
 data = 0.0;
next = NULL;
}
list(int dat)
{
data =dat;
next = NULL;
}
void insert(list *node);
void display(list *);
};
template<class T>
void list<T>::insert(list<T> *node)
{
list *last = this;
while(last ->next)
last = last ->next;
last->next = node;
}
template<class T>
void list<T>::display(list<T> *first)
{
list *traverse;
for(traverse=first;traverse;traverse=traverse->next)
cout<<traverse->data;
cout<<endl;
}
void main()
{
int choice1,data;
list<int> *first = NULL;
list<int> *node;
while(1)
{
cout<<"\n Linked list using Templates";
cout<<"\n 1. Insert the element";
cout<<"\n 2. Display the elements:";
cout<<"\n 3. Quit";
cout<<"\n Enter your choice:";
cin>>choice1;
switch(choice1)
{
case 1:
cout<<"\n enter data:";
cin>>data;
node=new list<int>(data);
if(first==NULL)
first = node;
else
first -> insert(node);
break;
case 2:
first ->display(first);
break;
case 3:
exit(1);
}
}
}






OUTPUT:

 Linked list using Templates
 1. Insert the element
 2. Display the elements:
 3. Quit
 Enter your choice:1

 enter data:12

 Linked list using Templates
 1. Insert the element
 2. Display the elements:
 3. Quit
 Enter your choice:1

 enter data:23

 Linked list using Templates
 1. Insert the element
 2. Display the elements:
 3. Quit
 Enter your choice:1

 enter data:10

 Linked list using Templates
 1. Insert the element
 2. Display the elements:
 3. Quit
 Enter your choice:2
12 23 10

 Linked list using Templates
 1. Insert the element
 2. Display the elements:
 3. Quit
 Enter your choice:3

RESULT:
Thus the program for linked list using template was executed using C++ .

0 comments:

Post a Comment