I want to do it as general as possible so I don't want to start with some designing errors that I will see after a week when it will be too late and I'll need to redo a huge part of my project.
I know that every node will be a list entry and that it will point to the next list entry, but I need some help designing this (a quick example will be just enough to kick things off).
EDIT:
1 2 3 4 5 6 7 8 9
template<typename Element>
class LinkedList
{
public:
// constructor, destructor etc
private:
LinkedList *next;
Element e;
};
The first example was better. A list is a collection of nodes, and should therefore be separate objects. I would start this project like so:
1 2 3 4 5 6 7 8 9 10
template <typename T>
class LinkedList
{
private:
struct Node
{
T data;
Node* next;
} *head;
};
What this does is makes it so the end user has no idea about a Node. It also allows you to store things like size as member variables of the LinkedList
template<typename Element>
class Nod;
typedef Nod *PNod;
template<typename Element>
class Nod
{
private:
Element e;
PNod next;
public:
friendclass SingleLinkedList;
// constructor
template<typename Element>
Nod(Element newE, PNod nextE = 0)
{
this->e = newE;
this->next = next;
}
template<typename Element>
Element getElement()
{
return e;
}
PNod getNext()
{
return next;
}
};
/*
* iterator
*/
class Iterator {
public:
friendclass SingleLinkedList;
void prim();
void next()
{
curent = curent->getNext();
}
int hasNext()
{
return curent != 0;
}
template<typename Element>
Element elem()
{
return curent->getElement();
}
private:
Iterator(PNod &first)
{
curent = first;
}
PNod curent;
};
/*
*
*/
class SingleLinkedList {
public:
friendclass Iterator;
SingleLinkedList() : prim(0)
{
}
~SingleLinkedList();
Iterator* iterator()
{
Iterator *i = new Iterator(prim);
return i;
}
/**
* Add an element to the list
* e - element
*/
template<typename Element>
void add(Element e);
private:
PNod prim;
/*
* Return the first element in the iteration
*/
PNod first()
{
return prim;
}
/*
* Get the next element
*/
PNod next(PNod p)
{
return p->getNext();
}
};
SingleLinkedList::~SingleLinkedList()
{
while (prim != 0) {
PNod p = prim;
prim = prim->next;
delete p;
}
}
template<typename Element>
void SingleLinkedList::add(Element e)
{
if (!prim)
prim = new Nod(e);
else {
PNod p = prim;
for (; p->next; p = p->next)
;
PNod q = new Nod(e);
p->next = q;
}
}
But I think I lost something(s) on the road when it comes to templates and/or friend classes because I get all kinds of errors: from "field next could not be resolved" in SingleLinkedList::~SingleLinkedList() to "shadow template parm 'class Element' " on template<typename Element> class Nod.
I'll try to implement the above with an Iterator friend class while waiting for some light on the mess I made here.