Monday, August 31, 2009

How to create doubly linklist using template in c++

First create list.h file and put this code in list.h

#include "list.h"
#include
using namespace std;

template<> class Lnode
{
public:
T data;
Lnode<> *next;
Lnode<> *prev;

};


template<> class List
{
public:
void add( T data );
void display();
T remove();
Lnode<>* head;
List()
{
head = new Lnode<>();
head->next = NULL;
head->prev = NULL;
}
};

template<> void List<>::add( T data )
{
Lnode<> *p;
p = new Lnode<>();
p->data = data;
p->next = head->next;
p->prev = head->prev;
head->next = p;
}

template<> T List<>::remove()
{
T data;
Lnode<> *node;

if (head->next == NULL)
{
cout << "ERROR: `remove' called with empty list.\n"; exit(1); } node = head->next;
data = node->data;

head->next = node->next;
head->prev = node->prev;
delete node;

return data;
}

template<> void List<>::display()
{
T data;
Lnode<> *node;

while(head->next!= NULL)
{

head=head->next;
cout <<>data;
cout << "\n"; } }

Next create linklist_template.cpp and put this code in linklist_template.cpp.

#include "list.h"
#include
using namespace std;

int main()
{
List<> list1;
List<> list2;

list1.add( 5 );
list1.add( 25 );
list1.add( 35 );
list1.add( 45 );
list2.add( 2.7 );

list1.display();

cout << list1.remove();
cout << "\n";
cout << list1.remove();
cout << "\n";
cout << list1.remove();
cout << "\n";

l

return 0;
}

No comments:

Post a Comment