C++写的一个List<T>
#include "stdafx.h"
#include <iostream>
using namespace std;
template<typename T>
struct Node
{
T value;
Node* next;
Node* pre;
};
template<typename T>
class List
{
private:
Node<T>* head;
Node<T>* current;
Node<T>* create;
int number ;
public:
List()
{
head=new Node<T>();
head->next=NULL;
head->pre=NULL;
current=head;
number=0;
}
~List(){
Node<T> * temp=current;
while (temp->next!=NULL)
{
temp=temp->next;
delete(temp->pre);
}
if (temp->next==NULL)
{
delete(temp);
}
cout<<"析构完成"<<endl;
}
void Add(T a)
{
create=new Node<T>();
create->value=a;
create->next=current;
create->pre=NULL;
current->pre=create;
current=create;
number++;
}
bool Contains(T a){
Node<T> * temp=current;
bool ret=false;
while (temp->next!=NULL)
{
if (temp->value==a)
{
ret=true;
break;
}
temp=temp->next;
}
return ret;
}
void Remove(T a){
Node<T> * temp=current;
while (temp->next!=NULL)
{
if (temp->value==a)
{
number--;
if (temp->pre!=NULL)
{
temp->pre->next=temp->next;
temp->next->pre=temp->pre;
delete(temp);
}
else
{
current=current->next;
delete(temp);
}
break;
}
else
{
temp=temp->next;
}
}
}
void Display()
{
Node<T> * temp=current;
while (temp->next!=NULL)
{
cout<<temp->value<<endl;
temp=temp->next;
}
}
int getNumber(){
return number;
}
};
void Test()
{
List<int> *p=new List<int>();
for (int i=0;i<3553;i++)
{ p->Add(i);
}
p->Display();
cout<<"个数:"<<p->getNumber()<<endl;
getchar();
cout<<p->Contains(333)<<endl;
delete(p);
}
int main()
{
Test();
getchar();
return 0;
}