#include
#include "List.h"
using namespace std;
int main() {
#include <iostream>
#include "List.h"
using namespace std;
int main() {
int size = 5;
List<int> numbers;
for(int i = 0; i < size; i++)
{
numbers.addHead(i);
}
cout << numbers.showList();
return 0;
}
}
List.h
#include
using std::string;
template
class Link
{
private:
T value;
Link* next;
public:
//constructor
Link(T value, Link* next = nullptr): value(value), next(next){}
//destructor
virtual ~Link(){}
//return value
T getValue(){return this->value;}
//return next
Link* getNext(){return this->next;}
//set next
void setNext(Link* next){this->next = next;}
};
template
class List
{
private:
Link* head;
public:
List():head(nullptr){}
//virtual ~List();
void addHead(T value);
#include <string>
using std::string;
template <typename T>
class Link
{
private:
T value;
Link* next;
public:
//constructor
Link(T value, Link* next = nullptr): value(value), next(next){}
//destructor
virtual ~Link(){}
//return value
T getValue(){return this->value;}
//return next
Link* getNext(){return this->next;}
//set next
void setNext(Link* next){this->next = next;}
};
template <typename T>
class List
{
private:
Link<T>* head;
public:
List():head(nullptr){}
//virtual ~List();
void addHead(T value);
//for testing
string showList()
{
string buffer = "";
if(head == nullptr)
{
buffer = "Nothing in the List";
}
else
{
buffer = "Head -> ";
for(Link<T>* currentLink = head; currentLink; currentLink = currentLink->getNext())
{
buffer += std::to_string(currentLink->getValue());
buffer += " -> ";
}
buffer += "nullptr";
}
return buffer;
}
};
};
List.cpp
#include "List.h"
template
void List::addHead(T value)
{
Link* theLink;
theLink = new Link(value);
theLink->setNext(head);
head = theLink;
}
#include "List.h"
template <typename T>
void List<T>::addHead(T value)
{
Link<T>* theLink;
theLink = new Link<T>(value);
theLink->setNext(head);
head = theLink;
}