#include<iostream>
using namespace std;
template<class T>
class list{
public:
list()
{
cout<<"^";
head=new list<T>;
length=0;
}
list(T value,list<T>* next1)
{
data=value;
next=next1;
}
bool Insert(T value,int i);
int Findvalue(T value);
list<T>* Findi(int i);
bool Remove(int i);
void display();
T Display()
{
return data;
}
list<T>* Head()
{
return head;
}
int Length()
{
return length;
}
protected:
list<T>* head;
T data;
list<T>* next;
int length;
};
template<class T>
list<T>* list<T>::Findi(int i)
{
if(i<0||i>length)
return NULL;
if (i==0)
return head;
int j=1;
list<T>* p=head->next;
if (j<i&&p!=NULL)
{
p=p->next;
j++;
}
cout<<"Findi ok!"<<endl;
return p;
}
template<class T>
bool list<T>::Insert(T value,int i)
{
cout<<"Insert 1 ok!"<<endl;
list<T>* p=Findi(i-1);
if (p==NULL)
{
cout<<"so sad~"<<endl;
return false;
}
list<T>* newp = new list<T>(value,p->next);
if (newp==NULL)
return false;
p->next=newp;
length++;
cout<<"Insert ok!"<<endl;
return true;
}
template<class T>
int list<T>::Findvalue(T value)
{
list<T>* p=head->next;
int i=1;
while (i<length&&p->data!=value)
{
p=p->next;
i++;
}
cout<<"Findvalue ok!"<<endl;
return i;
}
template<class T>
bool list<T>::Remove(int i)
{
list<T>* p=Findi(i-1),*q;
if (p==NULL)
return false;
q=p->next;
p->next=q->next;
delete q;
length--;
cout<<"Remove ok!"<<endl;
return true;
}
template<class T>
void list<T>::display()
{
list<T>* p=head->next;
int i=1;
while (i<=length)
{
cout<<p->data<<" ";
i++;
p=p->next;
}
cout<<"display ok!"<<endl;
cout<<endl;
}
int main()
{
list<int> list1;
int num;
int i=1,j=0;
while (1)
{
cin>>num;
list1.Insert(num,i);
i++;
cout<<"ok ";
if (cin.get()=='\n')
{
cout<<"break!"<<endl;
break;
}
}
int num1;
cin>>num1;
j=list1.Findvalue(num1)-1;
list1.Remove(j);
list1.display();
}
编译结果是重复出现^符号,且无法输入数据。当我把构造函数中的new list那里改为null以后,就可以输入数据了。