Loading....
Coupon Accepted Successfully!

 

Linked Lists With Templates

The linked lists are one of the popular data structures. The following program explains the working of a linked list with templates.
 
17.18 Write a program to create linked list with template class
#include<iostream.h>
#include<constream.h>
template <class L>
class list
{
L t;
list *next;
public:
list ( L t);
void add_num (list *node)
{
node->next=this;
next=NULL;
}
list *obtainnext() {return next;}
L getnum() {return t;}
};
template <class L> list <L>::list (L y)
{
t=y;
next=0;
}
void main()
{
clrscr();
list <int> obj(0);
list <int> *opt, *last;
last=&obj;
int j=0;
while (j<15)
{
opt=new list <int> (j+1);
opt->add_num (last);
last=opt;
j++;
}
opt=&obj;
j=0;
while (j<15)
{
cout<<opt->getnum() << “ ”;
opt=opt->obtainnext();
j++;
}
}
OUTPUT
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
 
Explanation: In the above program, the class template is declared same as in the previous programs. The class list has two arguments. One is of template L type (t), and the other is an object of the class list (*next). The pointer next is a pointer to the next element of the linked list. The add_num() function is used to add successive numbers in the linked list. The function obtain next() function returns the address of the next element. The function declarator of the obtain next() is preceded by the symbol ‘*,’ because it returns the address of the element. In the function add_num(), the next pointer is initialized with zero, that is, the next element is initialized to zero. If we do not initialize the next with zero, it will become a wild pointer and may point to any location of the system. Using a loop, successive numbers are added and displayed.




Test Your Skills Now!
Take a Quiz now
Reviewer Name