关于动态建立链表
以下代码是《C程序设计》(第四版)里的例题
是动态建立链表的,我按着书上的一个字符不差的敲到VC++6.0的编译器里,结果程序编译通过了
只是运行后只能输入一次数据就出错退出了。
运行环境为:WINDOWS 7+VC++6.0
不知道这是我运行环境问题呢还是这代码有问题呢?请高手给看看。
#include <stdio.h>动态链表 C描述 VC++ 出错
#include <stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student * next;
};
int n;
struct Student * creat(void)
{
struct Student * head;
struct Student * p1,* p2;
n=0;
p1=p2=(struct Student *)malloc(LEN);
scanf("1d,%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LEN);
scanf("1d,%f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
int main()
{
struct Student * pt;
pt=creat();
printf("\nnum: %1d\nscore: %5.1f\n",pt->num,pt->score);
free(pt);
return 0;
}
Student * creat(void)
{
Student *head = NULL;
Student *last = NULL;
Student *newNode = (Student *)malloc(LEN);
scanf_s("%ld%f",&(newNode->num), &(newNode->score));
head = last = newNode;
while(true)
{
newNode = (Student *)malloc(LEN);
scanf_s("%ld%f",&(newNode->num), &(newNode->score));
if(newNode->num == 0)
break;
last->next = newNode;
last = last->next;
}
last->next = NULL;
return head;
}