# 链表的定义

//链表的定义 头文件
template<class T>
class ChainNode{
friend Chain<T>
private:
T Data;		//数据域
}
template <class T>
class Chain{
public:
Chain(){first=0;}
~Chain();
bool IsEmpty()const{return first==0;}
int Length()const;
bool Find(int k,T& x)const;
int Search(const T& x)const;
Chain<T>& Delete(int k,T& x);
Chain<T>& Insert(int k,const T& x);
void Output(ostream& out)const;
private:
ChainNode<T> *first;
}
template<class T>
Chain::~Chain()
{
ChainNode *next;
while(first){
delete next;
first=next;
}
}
template<class T>
int Chain<T>::Length()const;
{
ChainNode<T> *current=first;
int len=0;
while(current){
len++;
}
return len;
}
template<class T>
bool Chain<T>::Find(int k,T& x)const
{//寻找第k个元素将其传送到x;
if(k<1)return false;
ChainNode<T> *current=first;
int index=1;
while(index<k&¤t){
index++;
}
if (current){x=current->Data;return true;}
return false;
}
template<class T>
int Chain<T>::Search(const T& x)const;
{
ChainNode<T> *current=first;
int index=1;
while(current&¤t->Data!=x){
index++;
}
if(current){return index;}
return 0;
}
template<class T>
Chain<T>& Chain<T>::Delete(int k,T& x)//返回一个引用表示返回*this本身
{//把第k个元素取至x然后从链表中删除第k 个元素
//如果不存在第k 元素则找不到引发异常
if(k<1||!first)		//如果不存在first
cerr<<"wrong to find the number:"<<endl;//找不到第K个元素 输出错误
ChainNode<T> *p=first;	//P最终指向第k个节点
if(k==1)		//p已经指向第k个元素 因为p的初始化是first
else		//用q指向第k-1个元素
ChainNode *q=first;}
for(int index=1;index<k-1&&q;index++)
cerr<<"can not find the number"<<endl;//不存在第k个元素
x=p->Data;
//保存第k个元素并释放节点p
delete p;
return *this
}
template<class T>
Chain<T>& Chain<T>::Insert(int k,const T& x)
{	//第k个元素之后插入x
if(k<0)//不存在k;
cerr<<"can not find\n";
ChainNode<T> *p=first;	//p最终指向第k个节点
for(int index=1;index<k&&p;index++)
if(k<0&&!P)cerr<<"x is not exit\n";//不存在第k个元素
ChainNode<T> *y=new ChainNode<T>;
y->Data=x;
if(k){		//在p之后插入 ;
else{		//作为第一个元素插入
first=y;}
return *this;
}
template<class T>
void Chain<T>::Output(ostream& out)const;
{
ChainNode<T> *current;
out<<current->Data<<" ";
}
//重载<<
template<class T>
ostream& operator<<(ostream& out,const Chain<T>& x)
{x.Output;return out;}

• 写评论