为什么会是死循环?
struct student *creat(); //创建链表void print(struct student *head);//打印链表
struct student
{
int num;
int score;
struct student *next;
};
int n;//全局,用来记录存放了多少数据
int main()
{
struct student *stu;
stu = creat();
print(stu);
printf("\n\n");
system("pause");
}
struct student *creat()
{
struct student *p1, *p2, *head;
p1 = p2 = (struct student *)malloc(sizeof(struct student));//给p1,p2 申请动态存储空间
printf("请输入学号:");
scanf("%d", &p1->next);
printf("请输入成绩:");
scanf("%d", &p1->score);
head = NULL;
n = 0;
while (p1->num)
{
n++;
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct student *)malloc(sizeof(struct student));
printf("请输入学号:");
scanf("%d", &p1->next);
printf("请输入成绩:");
scanf("%d", &p1->score);
}
p2->next = NULL;
return head;//返回一个链表的头指针(头节点)相当于数组首地址
};
void print(struct student *head)//首先要知道链表第一个节点的地址,也就是head的值
{
struct student *p;
/*设一个指针变量p,先指向第一个节点(head)
然后输出p所指的节点,然后使p后移一个节点,在输出,直到链表尾标志NULL */
printf("\n\n共输入了%d名学生资料\n", n);
p = head;
if (head)
{
do
{
printf("学号:%d的成绩是:%d\n", p->num, p->score);
p = p->next;//p后移一个节点
} while (p);
}
} 你的判断条件是while (p1->num)但是你的循环中没有修改过p1->num的值,你修改的是p1->next
scanf("%d", &p1->next);我理解你的程序应该是这一句错了 我改过来了 的确是scanf("%d", &p1->next) 错了 谢啦
页:
[1]