2 crazymonk CrazyMonk 于 2015.06.18 22:44 提问

C语言链表创建问题..123

#include"stdafx.h"
#include
#define LEN sizeof(student)
struct student{
int num;
float score;
student *next;
};
student * creat(){
int num;
float score;
student *head, *p,*q;

q=p=head = (student *)malloc(LEN);
head->num = NULL;
scanf_s("%d%f",&num,&score);
while (num != 0)//如果输入0的话就当成结束
{
    p = (student*)malloc(LEN);
    p->num = num;
    p->score = score;
    p->next = NULL;
    q->next = p;
    q = p;
    scanf_s("%d%f",&num,&score);
}
p->next = NULL;
return head;

}
void print(student * head){
student *p;
p = head;
for (; p->next != NULL;)
{
printf("%d %f", p->next->num, p->next->score);
p = p->next;
}

}
void main(){
student *head;
creat();
head = creat();
print(head);

}
//我输入
1 20
2 30
3 40
0 10
的话没有输出什么东西啊

6个回答

fxbjye
fxbjye   2015.06.19 10:05
已采纳

主函数里为什么会有两个creat函数调用,我把你的代码测试了一下,去掉第一个creat 是可以运行成功的,也有输出信息。另外你的代码缺少标准库能编译通过吗?希望有所帮助。
#include
#include
#define LEN sizeof(student)

struct student{
int num;
float score;
student *next;
};

student * creat(){
int num;
float score;
student head, *p,*q;
q=p=head = (student *)malloc(LEN);
head->num = NULL;
scanf("%d%f",&num,&score);
while (num != 0)//如果输入0的话就当成结束
{
p = (student
)malloc(LEN);
p->num = num;
p->score = score;
p->next = NULL;
q->next = p;
q = q->next;
scanf("%d%f",&num,&score);
}
p->next = NULL;
return head;

}
void print(student * head){
student *p;
p = head;
for (; p->next != NULL;)
{
printf("%d %f", p->next->num, p->next->score);
p = p->next;
}

}
int main(){
student *head;
head = creat();
print(head);

return 0;
}

weixin_28693239
weixin_28693239   2015.06.18 22:59

什么都没输出么?
应该输出了head所指向的头节点空间地址吧

angle118114
angle118114   2015.06.18 23:04

你的main里怎么有两个creat().....

sinat_29089007
sinat_29089007   2015.06.19 00:42

在函数student* create()写的有问题。你想要加入学生的学号,成绩,姓名信息,使用了链表。但是你的create函数并没有真正的给你创建信息。因为你需要在函数调用之前传入你要创建的student结构体,所以要传参。另外你的头结点使用并不正确,可以在看看书上的代码。感觉利用顺序存储结构(使用数组)会更简单些。希望有帮助

solio5
solio5   2015.06.19 11:05
 p->num = num;
    p->score = score;
    p->next = NULL;
    q->next = p;
    q = p;
    scanf_s("%d%f",&num,&score);

这个应该先调用scanf_s,再给p->num = num; 赋值

zxh707wk
zxh707wk   Rxr 2015.06.21 23:29
Csdn user default icon
上传中...
上传图片
插入图片