#ifndef list_HH
#define list_HH
#include
#include
#include
/*
author 王金龙
QQ: 1473371475
*/
using namespace std;
template
struct Node
{
type value;
Node *next;
};
template
class List
{
private:
int len;
Node *head;
public:
List();
~List();
bool add(type);
bool remove(int index);
type getValue(int index);
int getIndex(type value);
int getLength();
void traverse();
};
template
List::List()
{
head = (new Node());
len = -1;
head->next = NULL;
}
template
bool List::add(type value)
{
try{
if(len == -1)
{
if(head == NULL)
{
head = (new Node());
len = -1;
}
head->value = value;
head->next = NULL;
len++;
return true;
}
Node *temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
Node *node = new Node();
node->value = value;
node->next = NULL;
temp->next = node;
++len;
return true;
}catch(...){}
return false;
}
template
bool List::remove(int index)
{
if(index > len || index < 0)
{
return false;
}
Node *aTemp = head;
Node *pTemp = NULL;
int count = 0;
while(count <= len)
{
if(count == index && index == 0)
{
head =aTemp->next;
free(aTemp);
aTemp = NULL;
len--;
break;
}
if(count == index)
{
pTemp->next = aTemp->next;
free(aTemp);
len--;
aTemp = NULL;
break;
}
pTemp = aTemp;
aTemp = aTemp->next;
count++;
}
return true;
}
template
int List::getLength()
{
return len+1;
}
template
type List::getValue(int index)
{
if(index < 0 || index > len)
{
return NULL;
}
Node * temp = head;
int count = 0;
while(count <= len)
{
if(count == index)
{
return temp->value;
}
temp = temp->next;
count++;
}
return NULL;
}
template
int List::getIndex(type value)
{
if(len == -1)
{
return -1;
}
Node *temp = head;
int count = 0;
while(count <= len)
{
type v = temp->value;
if(v == value)
{
return count;
}
temp = temp->next;
count++;
}
return -1;
}
template
void List::traverse()
{
if(len == -1)
{
return;
}
Node *temp = head;
int count = 0;
while(count <= len)
{
cout << temp->value << ", ";
temp = temp->next;
++count;
}
cout << endl;
}
template
List::~List()
{
Node *temp = head;
Node *temp1 = NULL;
int count = 0;
while(count <= len)
{
temp1 = temp;
temp = temp->next;
if(temp1 != NULL)
{
delete temp1;
temp1 = NULL;
}
count++;
}
}
#endif