一个简单的链表 帮忙看看

来源:百度知道 编辑:UC知道 时间:2024/05/28 03:46:37
想就用一个主函数,先输入要输入的个数,然后分别输入姓名和分数,最后打印出来
自己写了一个错得厉害帮忙改改 自己加了注释了
#include<stdio.h>
#include<stdlib.h>

struct node
{
char name[20]; //名字
int num; //分数
struct node *next;
}*head,*p,*nod,*temp;

void main()
{
int i,j;
head = (struct node *)malloc(sizeof(struct node));
p=(struct node *)malloc(sizeof(struct node));
head->next=p;
printf("Input the number "); //输入人数
scanf("%d",&j);
for(i=0;i<j;i++)
{

p=(struct node *)malloc(sizeof(struct node));
printf("Input the name");
gets(p->name);
printf("Input the num");
scanf("%d",&p->num);
p->next=p; //这里写得很不对。。。。自己也知道 不知道怎么改
}
for(i=0;i<j;i++)
{
printf("%s %d\n",p->name,p->num);
p=p->next;
}

}

错得真不少,
这么改,具体说明请看注释:

#include<stdio.h>
#include<stdlib.h>
struct node
{
char name[20];
int num;
struct node *next;
}*head,*p,*nod,*temp;

void main()
{
int i,j;
head = (struct node *)malloc(sizeof(struct node));
// p=(struct node *)malloc(sizeof(struct node)); //这里不用创建p指向空间
// head->next=p; //head此时还没有赋值,所以先不要将其next结点挂上
p=head;//将p作为指向当前赋值结点的指针
printf("Input the number ");
scanf("%d",&j);
for(i=0;i<j;i++)
{

// p=(struct node *)malloc(sizeof(struct node)); //p已经指向了需要扶植的节点,不需要再度申请空间
printf("Input the name: "); //输出加个:好看一些
fflush(stdin);//强制清空键盘缓冲区,防止将上次输入的回车读入
gets(p->name);
printf("Input the num: "); //输出加个:好看一些
fflush(stdin);//强制清空键盘缓冲区,防止将上次输入的回车读入
scanf("%d",&p->num);
// p->next=p; //这里这么写就变成一个循环指向的结点了,所以不对