链表的定义

//链表的定义 头文件
template<class T>
class ChainNode{
friend Chain<T>
private:
T Data;		//数据域
ChainNode<T> *link;//指针域
}
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){
	next=first->link;
	delete next;
	first=next;
	}
}
template<class T>
int Chain<T>::Length()const;
{
	ChainNode<T> *current=first;
	int len=0;
	while(current){
	len++;
	current=first->link;
	}
	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){
	current=current->link;
	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){
	current=current->link;
	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
	{first=first->link;//删除 第一个节点
	else		//用q指向第k-1个元素 
	ChainNode *q=first;}
	for(int index=1;index<k-1&&q;index++)
	q=q->link;	//找到p 即是k-1 个元素
	if(!q||q->link)
	cerr<<"can not find the number"<<endl;//不存在第k个元素  
	p=q->link;//存在第k个元素  q的指针域指向p  
	q->link=p->link;//删除第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++)
	p=p->link;	//将p移动到第k个节点
	if(k<0&&!P)cerr<<"x is not exit\n";//不存在第k个元素
	ChainNode<T> *y=new ChainNode<T>;	
	y->Data=x;
	if(k){		//在p之后插入 ;
	y->link=p->link;
	p->link=y;}
	else{		//作为第一个元素插入 
	y->link=first;
	first=y;}
	return *this;
}
template<class T>
void Chain<T>::Output(ostream& out)const;
{
	ChainNode<T> *current;
	for(current=first;current;current=current->link)
	out<<current->Data<<" ";
}
//重载<<
template<class T>
ostream& operator<<(ostream& out,const Chain<T>& x)
{x.Output;return out;}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值