c语言链表问题 求大神给看看 运行后只能输入一组数据,而且输出乱码
#include<stdio.h>#include<stdlib.h>structStudent//创建节点{charcName[20];intiNum;structSt...
#include<stdio.h>#include<stdlib.h>struct Student //创建节点{ char cName[20]; int iNum; struct Student * pNext;}; //节点后要加分号struct Student * create_list(void){ int i; int iSum; struct Student * pHead=(struct Student *)malloc(sizeof(struct Student)); //初始化头指针 if(pHead==NULL) { printf("memory allocation failed!program stop!\n"); exit(-1); } struct Student * pEnd=pHead; //定义pEnd 让pHead中的pNext指向NULL pEnd->pNext=NULL; printf("Please enter the sum of class:"); //设置节点数 scanf("%d",&iSum); printf("\n"); for(i=0;i<iSum;i++) { struct Student * pNew=(struct Student *)malloc(sizeof(struct Student)); //动态的分配空间 if(pNew==NULL) { printf("memory allocation failed! program stop!"); exit(-1); } printf("name:"); scanf("%s",&pEnd->cName); printf("NO."); scanf("%d",&pEnd->iNum); //为节点中数据赋值 pEnd->pNext=pNew; //动态的指向 pNew->pNext=NULL; pEnd=pNew; return pHead; }}void Print(struct Student * pHead){ struct Student * pTemp=pHead->pNext; while(pTemp!=NULL) { printf("%d %s",pTemp->iNum,pTemp->cName); pTemp=pTemp->pNext; printf("\n"); } printf("\n");}void main(){ struct Student * pHead=NULL; pHead=create_list(); Print(pHead);}
展开
1个回答
2016-07-01
展开全部
修改如下:
#include<stdio.h>
#include<stdlib.h>
struct Student
{
char cName[20];
int iNum;
struct Student * pNext;
};
struct Student * create_list(void)
{
int i;
int iSum;
struct Student * pHead=NULL;//注意这里
struct Student * pEnd=NULL; //注意这里
struct Student * pNew=NULL; //注意这里
printf("Please enter the sum of class:");
scanf("%d",&iSum);
printf("\n");
for(i=0;i<iSum;i++)
{
pNew=(struct Student *)malloc(sizeof(struct Student)); //注意这里
if(pNew==NULL)
{
printf("memory allocation failed! program stop!");
exit(-1);
}
printf("name:");
scanf("%s",&pNew->cName); //注意这里
printf("NO.");
scanf("%d",&pNew->iNum); //注意这里
pNew->pNext=NULL; //注意这里
if (pHead==NULL) { //注意这里
pHead=pNew; //注意这里
}
else pEnd->pNext=pNew; //注意这里
pEnd=pNew; //注意这里
}
return pHead; //注意这里
}
void Print(struct Student * pHead)
{
//注意这里
while(pHead!=NULL) //注意这里
{
printf("%d %s",pHead->iNum,pHead->cName); //注意这里
pHead=pHead->pNext; //注意这里
printf("\n");
}
printf("\n");
}
void main()
{
struct Student * pHead=NULL;
pHead=create_list();
Print(pHead);
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询