#include <cstdlib>
#include <iostream>
using namespace std;
template <typename T>
class List
{
public:
List();
~List();
void push_back(const T&);
void print();
void reverse();
void check(const T);
void del(const T);
private:
typedef struct Node
{
T data;
Node* next;
Node(const T& d):data(d),next(NULL){}
}Node;
Node* head;
};
template <typename T>
void List<T>::del(const T t)
{
typedef Node* PNode;
PNode pre,cur;
pre = head;
cur = pre->next;
while(cur->data != t)
{
pre = cur;
cur = cur->next;
}
pre->next = cur->next;
delete cur;
}
template <typename T>
List<T>::List():head(NULL){}
template <typename T>
List<T>::~List()
{
if(head)
{
Node* t = head->next;
while(t)
{
Node* tt = t;
t = t->next;
delete tt;
}
delete head;
head = NULL;
}
}
template <typename T>
void List<T>::push_back(const T& t)
{
if(!head)
head = new Node(t);
else
{
Node* tmp = head;
while(tmp->next)
{
tmp = tmp->next;
}
tmp->next = new Node(t);
}
}
template <typename T>
void List<T>::print()
{
if(head)
{
Node* t = head;
while(t)
{
cout << t->data << " ";
t = t->next;
}
cout << endl;
}
}
template <typename T>
void List<T>::reverse()
{
if(head && head->next)
{
typedef Node* PNode;
PNode pre = head, cur = head->next, nex = cur->next;
pre->next = NULL;
while(nex)
{
cur->next = pre;
pre = cur;
cur = nex;
nex = nex->next;
}
cur->next = pre;
head = cur;
}
}
template <typename T>
void List<T>::check(const T t)
{
Node* tmp = head;
int times = 0;
while(/*tmp->data != t && */tmp->next != NULL)
{
if(tmp->data == t){
cout << "found " << t << " in the list!" << endl;
times++;
break;
}
tmp = tmp->next;
}
if(times == 0)
cout << t << " not found in the list!" << endl;
}
int main(int argc, char *argv[])
{
List<int> list1;
for(int i = 0; i < 50; ++i)
list1.push_back(i);
list1.print();
int a = 25;
list1.check(a);
list1.del(a);
list1.print();
list1.check(a);
system("PAUSE");
return EXIT_SUCCESS;
}