首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于动态建立链表,该怎么处理

2013-01-23 
关于动态建立链表以下代码是《C程序设计》(第四版)里的例题是动态建立链表的,我按着书上的一个字符不差的敲

关于动态建立链表
以下代码是《C程序设计》(第四版)里的例题
是动态建立链表的,我按着书上的一个字符不差的敲到VC++6.0的编译器里,结果程序编译通过了
只是运行后只能输入一次数据就出错退出了。
运行环境为:WINDOWS 7+VC++6.0
不知道这是我运行环境问题呢还是这代码有问题呢?请高手给看看。

#include <stdio.h>
#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;

}
动态链表 C描述 VC++ 出错
[解决办法]

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;
}

把第一个节点的创建放在循环的外面来做,这样子就能把循环简化了

热点排行
Bad Request.