#include?<iostream>
using?namespace?std;
#include?<stdlib.h>
struct?list
{?
int?data;
struct?list?*next;
};
struct?list?*?creatlist()??//創建一個帶頭結點的單向鏈表,鏈表結點中的數據通過鍵盤輸入,當輸入數據為-1時,表示輸入結束。
{
struct?list?*p1,*p2,*head;
int?n=1;
head=NULL;
p1=p2=(?struct?list*)malloc(sizeof(struct?list));
cout<<"number"<<endl;
cin>>p1->data;
while(p1->data!=(-1))
{
if(n==1)head=p1;
else?p2->next=p1;
p2=p1;
free(p1);
cin>>p1->data;
}
p2->next=NULL;
return(head);
}
void?print(list?*L)??//打印鏈表
{
??struct?list?*p;
??p=L;
??do
??{
??cout<<p->data<<endl;
??p=p->next;
??}while(p!=NULL);
}
void?Comput(list?*L)??//求其數據域的總和與平均值
{
struct?list?*p;
int?n,x;
n=x=0;
p=L;
while(p!=NULL)
{
x+=p->data;
p=p->next;
n++;
}
n=x/n;
cout<<"aver="<<n<<"sum="<<x<<endl;
}
void?main()?????
{
struct?list?*head;
head=creatlist();
print(head);
Comput(head);
}
1 回答

onemoo
TA貢獻883條經驗 獲得超454個贊
先說最明顯的。第 24 行,你把 p1 free 了! 那么 25 行再次訪問 p1 就已經不正確了!
而且,在 19 行的 while 循環中,由于 n 的值沒有變化,所以每次循環都會執行 21 行——也就是每次 head 和 p2 都指向 p1 所指的節點。? 但在第一次循環執行 24 行以后,p1 所指的節點已經不合法了,所以整個 while 就是不斷向一個不合法的內存中寫入數據!? 鏈表根本就沒有建立起來。
其他代碼還沒有看,但?creatlist 中的問題就不小了...
還有,你這個是 C++ 代碼吧?? ?在 C++ 中的沿襲的 C 語言庫函數的頭文件名并不是 C 語言風格的 xxx.h,而是 cxxx!? 比如 stdlib.h 這個 C 語言庫函數頭文件在 C++ 中應該寫 <cstdlib>。? 一個標準的 C++ 環境中就沒有?stdlib.h 這個頭文件!
- 1 回答
- 0 關注
- 920 瀏覽
添加回答
舉報
0/150
提交
取消