问题描述
- 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
的话没有输出什么东西啊
解决方案
主函数里为什么会有两个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;
}
解决方案二:
什么都没输出么?
应该输出了head所指向的头节点空间地址吧
解决方案三:
你的main里怎么有两个creat().....
解决方案四:
在函数student* create()写的有问题。你想要加入学生的学号,成绩,姓名信息,使用了链表。但是你的create函数并没有真正的给你创建信息。因为你需要在函数调用之前传入你要创建的student结构体,所以要传参。另外你的头结点使用并不正确,可以在看看书上的代码。感觉利用顺序存储结构(使用数组)会更简单些。希望有帮助
解决方案五:
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; 赋值
解决方案六:
参考代码段
https://github.com/707wk/Senior-middle-school/blob/master/Filling%20in%20the%20gaps.c