谭浩强 C语言教材上的一道建立动态链表的例题, 好像有错误?

来源:百度知道 编辑:UC知道 时间:2024/05/11 14:19:01
编译通过
运行的时候 如下:
input some records:
111,90
112,85
0,0
output your records:
0,0
正确的结果应该是下面这样才对啊?代码是书上一模一样的,感觉书上是p1传址给head,造成的错误?我应该怎么改呢?
input some records:
111,90
112,85
0,0
output your records:
111,90
112,85

*****************************
#include<stdio.h>
#include<math.h>

#define NULL 0
#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);
sqrt(99.0);
scanf("%ld,%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); sqrt(99.0);
scanf("%ld,%f",&p1->num,&p

n是creat函数用到的变量,你为什么放成全局变量?还有用sqrt(99.0)什么意思?del_num变量,struct student变量stu又是干什么用的?

我写的:
/************************************/
#include<stdio.h>
#include<math.h>

#define NULL 0
#define LEN sizeof(struct student)

struct student{
long num;
float score;
struct student *next;
};

struct student* creat(void){
struct student *head,*p1,*p2;
int n=0;
p1=p2=(struct student*)malloc(LEN);
p1->next=p2->next=NULL;
if(!p1)/*这里应该有个溢出处理的*/
sqrt(99.0);
scanf("%ld,%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0){
++n;
if(n==1)
head=p1;
else{
p2->next=p1;
p1->next=NULL;
p2=p1;
}
p1=(struct student *)malloc(LEN);
if(!p1)
sqrt(99.0);
scanf("%ld,%f",&p1->num,&p1->score);
}
return(head);
}