//head 是头节点,本身的link指向自己,first指向第一个真实的存储数据的节点
//头节点的初始化在构造函数中已经实现,但插入第一个节点是不知如何插入,还是头节点那样初始化根本就不对?
//在Chain类中只有first和head两个指针的情况下能否实现单向循环链表?
//请高手帮忙修改Insert(),其他的函数也帮忙改改,不胜感激
#include<iostream.h>
#include<stdlib.h>
/////////////////类定义//////////////////
template <class T>
class Chain;
template <class T>
class ChainNode
{
friend Chain<T>;
private:
T data;
ChainNode<T> *link;
};
template<class T>
class Chain
{
public:
Chain()
{
head=new ChainNode<T>;
head->link=first;
head->data=0;//head是不存储数据的头节点,头节点的LINK指向自己
}
~Chain();
Chain<T>& Insert(int k,const T&x);
void Output(ostream& out) const;
private:
ChainNode<T> *first,*head;//first是指向第一个真实数据的节点
};
//////////////析构函数///////////////////
template<class T>
Chain<T>::~Chain()
{
ChainNode<T> *next;
while(first)
{
next=first->link;
delete first;
first=next;
}
}
//////////////输出//////////////
template<class T>
void Chain<T>::Output(ostream& out) const
{
ChainNode<T> *current;
int index=0;
for(current=first;index<10;current=current->link)//输入3个数据,循环输出10个
{
out<<current->data<<" ";
index++;
}
}
template<class T>
ostream& operator<<(ostream& out,const Chain<T>& x)
{
x.Output(out);return out;
}
//////////////插入//////
template<class T>
Chain<T>& Chain<T>::Insert(int k,const T& x)
{
if(k<0) {cout<<"Error!";exit(1);}
ChainNode<T> *p=first;
for(int index=1;index<k&&p;index++)
p=p->link;
if(k>0&&!p) {cout<<"Error!";exit(1);}
ChainNode<T> *y=new ChainNode<T>;
y->data=x;
if(k)
{
y->link=p->link;
p->link=y;
}
else
{
//头节点如何插入
}
return *this;
}
////////////////主函数、测试/////////////////
void main()
{
Chain<int> L;
int ll;
cout<<L<<endl;
for(int i=0;i<3;i++)
{
cin>>ll;
L.Insert(i,ll);
}
cout<<"List is"<<L<<endl;
}
head 和first好像弄反了,head 是第一个存储真实数据的节点,first是不存储数据的头节点。
构造函数改为
Chain()
{
first=new ChainNode<T>;
first->link=first;
first->data=0;//first是不存储数据的头节点,头节点的LINK指向自己
}