// 学生成绩动态链表.cpp : 定义控制台应用程序的入口点。
//不带头节点
#include <stdio.h>
#include <malloc.h>
int n;
#define NULL 0
struct student
{
int num;
int score;
struct student *next;
};
struct student *creat()
{
n=0;
struct student *head;
struct student *p1, *p2;
head = NULL;
p1 = p2 = (struct student *)malloc(sizeof(struct student));
printf("请输入第一位学生的学号和成绩");
scanf("%d,%d",&p1->num,&p1->score);
while (p1->num != 0)
{
flushall();//清除缓存
n++;
if (n == 1)
head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct student *)malloc(sizeof(struct student));
printf("请输入学生学号和成绩");
scanf("%d,%d", &p1->num, &p1->score);
}
p2->next = NULL;
return(head);
}
void main()
{
struct student *p;
p = creat();
for (; p != NULL; p = p->next)
{
printf("%d",p->num);
printf(" ");
printf("%d",p->score);
}
//不带头节点
#include <stdio.h>
#include <malloc.h>
int n;
#define NULL 0
struct student
{
int num;
int score;
struct student *next;
};
struct student *creat()
{
n=0;
struct student *head;
struct student *p1, *p2;
head = NULL;
p1 = p2 = (struct student *)malloc(sizeof(struct student));
printf("请输入第一位学生的学号和成绩");
scanf("%d,%d",&p1->num,&p1->score);
while (p1->num != 0)
{
flushall();//清除缓存
n++;
if (n == 1)
head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct student *)malloc(sizeof(struct student));
printf("请输入学生学号和成绩");
scanf("%d,%d", &p1->num, &p1->score);
}
p2->next = NULL;
return(head);
}
void main()
{
struct student *p;
p = creat();
for (; p != NULL; p = p->next)
{
printf("%d",p->num);
printf(" ");
printf("%d",p->score);
}
}
出现的错误分析:1.死循环:原因处在scanf()函数,添加_flushall(),清除缓存,解决问题。
2.结果输出-81*****,第一个原因,head初始化不对,对于有头节点的,输出应从head->next开始,而我的错误出现在进行执行时,scanf逗号没有在英文下输入!