template <class T>
class RList
{
private:
//Structure that contains all information of the list
struct Data
{
T Value; //Value of the Element
Data *pNext; //Pointer to next Value
};
Data *pFirst; //Pointer to the first element of the list
Data *pTail; //Pointer to the last element of the list
int TotalObjects; //To save Count() performance
public:
//[] Operator implementation for the list
T& operator[] (int index)
{
if (index < 0 || index >= Count())
throw"Index out of range";
Data *p = pFirst;
for (int i = 0; i < index; ++i)
p = p->pNext;
return p->Value;
}
//Initialize the list
RList()
{
pFirst = NULL;
pTail = NULL;
TotalObjects = 0;
}
//Remove all list elements
~RList()
{
Clear();
}
//Add an element to the list
void Add(T value)
{
Data* pNew = (Data*)malloc(sizeof(Data));
pNew->Value = value;
pNew->pNext = NULL;
if (pFirst == NULL) {
pFirst = pNew;
pTail = pNew;
} else {
pTail->pNext = pNew;
pTail = pNew;
}
TotalObjects++;
}
//Insert an element at any position in the list
void InsertAt(T Value, int index)
{
if (index < 0 || index >= Count())
throw"Index out of range";
Data* pNew = (Data*)malloc(sizeof(Data));
pNew->Value = Value;
if (index == 0) {
pNew->pNext = pFirst;
pFirst = pNew;
} else {
Data *prev = pFirst;
Data *p = pFirst;
for (int i = 0; i < index; ++i) {
prev = p;
p = p->pNext;
}
prev->pNext = pNew;
pNew->pNext = p;
}
TotalObjects++;
}
//Counts all objects in the list
int Count()
{
return TotalObjects;
}
//Removes an element from the list
void RemoveAt(int index)
{
if (index < 0 || index >= Count())
throw"Index out of range";
if (index == 0) {
Data *p = pFirst->pNext;
if (pFirst == pTail)
pTail = p;
free (pFirst);
pFirst = p;
} else {
Data *prev = pFirst;
Data *p = pFirst;
Data *pNext = pFirst->pNext;
for (int i = 0; i < index; ++i) {
prev = p;
p = p->pNext;
pNext = p->pNext;
}
if (p == pTail)
pTail = prev;
free (p);
prev->pNext = pNext;
}
TotalObjects--;
}
//Clear all Objects in List
void Clear()
{
while (pFirst)
RemoveAt(0);
}
//Checks if a value is part of the list
bool Contains(T Value)
{
Data *p = pFirst;
while (p != NULL)
{
if (p->Value == Value)
returntrue;
p = p->pNext;
}
returnfalse;
}
};