如下这个链表为什么不能连多个点?

#include<iostream.h>
class CWnodeChain;

class CWnode
{
friend CWnodeChain;
private:
int data;
CWnode *link;
};

class CWnodeChain
{
public:
CWnodeChain(){first=0;}
~CWnodeChain();
int Length();
CWnodeChain Insert(int nd);
void Output();
private:

CWnode *first;
};

CWnodeChain::~CWnodeChain()
{
CWnode *p=first;
while(first)
{
p=first->link;
delete first;
first=p;
}
}

int CWnodeChain::Length()
{
CWnode *p;
int len=0;
for(p=first;p;p->link)
{

len++;
}

return len;
}

CWnodeChain CWnodeChain::Insert(int nd)
{

CWnode *q=new CWnode;

q->data=nd;
//从头接点插入
if(!first)
{
first=q;
}
else
{

q->link=first;
first=q;

}

return *this;
}

void CWnodeChain::Output() //输出
{
CWnode *p;
for(p=first;p;p=p->link)
cout<<p->data<<endl;

}

void main()
{

CWnodeChain obj;
cout<<obj.Length()<<endl;

obj.Insert(3);
cout<<obj.Length()<<endl;
obj.Output();

}

qq_遁去的一_1
浏览 168回答 1
1回答

MM们

1.CWnode没有构造函数,导致新生成的CWnode结点的link成员不是空,而是随机指向某个地址,导致错误.2.自己写类时,永远不要在某个函数中直接返回类对象,正确的方法是要么使用引用,要么返回指针.3.Length函数里,for循环的第三个部分写错了.正确代码如下:#include<iostream.h>class CWnodeChain;class CWnode{friend CWnodeChain;private:int data;CWnode *link;public: //加上默认构造函数CWnode():link(0){};};class CWnodeChain{public:CWnodeChain(){first=0;}~CWnodeChain();int Length();CWnodeChain &Insert(int nd); //返回类型用引用void Output();private:CWnode *first;};CWnodeChain::~CWnodeChain(){CWnode *p=first;while(first){p=first->link;delete first;first=p;}}int CWnodeChain::Length(){CWnode *p;int len=0;for(p=first;p;p=p->link) //原来你写的是p->link{len++;}return len;}CWnodeChain &CWnodeChain::Insert(int nd) //返回类型是引用{CWnode *q=new CWnode;q->data=nd;//从头接点插入if(!first){first=q;}else{q->link=first;first=q;}return *this;}void CWnodeChain::Output() //输出{CWnode *p;for(p=first;p;p=p->link)cout<<p->data<<endl;}void main(){CWnodeChain obj;cout<<obj.Length()<<endl;obj.Insert(3);cout<<obj.Length()<<endl;obj.Output();}
打开App,查看更多内容
随时随地看视频慕课网APP