从网上csdn博客搜到了一个群,里面的人提示我指针悬空了,还建议我把malloc改成new。他亲切地发出了下面的程序。为我调试过。从内容看,它的用语简明,又高手只用最小的代码调试错误的风范。
后来广州粉丝教我new应该怎么用。我得到了正确的程序结果。下面注释的部分是我调试时注释的。我加上了new那句。我一开始根本不知道new是什么东西,要放在哪里。
群主还自我介绍来自北京。还有大量的电子资料再在群文件。我如获至宝。感觉很亲切。
#include
#include
#include
using namespace std;
typedef struct data
{
int number;
string name;
string sex;
}data;
typedef struct listpoint
{
data *information;
listpoint *next;
listpoint *last;
listpoint *branch;
}listpoint;
/********************************************************/
listpoint *create_normal_list(int n)
{
listpoint *head,*normal,*end;
// head=(listpoint*)malloc(sizeof(listpoint));
head=new listpoint;
// head->information=(data*)malloc(sizeof(data));
head->information=new data;
end=head;
for(int i=0;i<n;i++)
{
// normal=(listpoint*)malloc(sizeof(listpoint));
normal=new listpoint;
// normal->information=(data*)malloc(sizeof(data));
normal->information=new data;
cout<<"input the number :";
cin>>normal->information->number;
cout<<"input the name :";
cin>>normal->information->name;
cout<<"input the sex :";
cin>>normal->information->sex;
cout<<"----------------------------------"<<endl;
end->next=normal;
normal->last=end;
end=normal;
}
end->next=NULL;
head->last=NULL;
return head;
}
listpoint *create_random_branch_list(int n)
{
listpoint *search_point(listpoint *list,int n);
listpoint *head;
head=create_normal_list(n);
listpoint *p,*bp;
p=head;
srand((int)(time(NULL)));
int randnum;
while((p=p->next)!=NULL)
{
randnum=rand()%n+1;
bp=search_point(head,randnum);
p->branch=bp;
}
return head;
int main()
{
listpoint *head;
head=create_random_sort_list(2);
system("pause");
return 0;
}
运行结果:
作者:千条数学课收藏夹分类
https://www.bilibili.com/read/cv7049937
出处: bilibili