亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如下這個鏈表為什么不能連多個點?

如下這個鏈表為什么不能連多個點?

qq_遁去的一_1 2022-08-05 11:07:01
#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();}
查看完整描述

1 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

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();

}


查看完整回答
反對 回復 2022-08-08
  • 1 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號