读书人

简单的有关问题

发布时间: 2012-02-04 15:43:08 作者: rapoo

简单的问题 在线等
#include <stdio.h>
#include <malloc.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 *p1,*p2;
struct student *head;
int n=0;
p1=p2=(struct student *)malloc(LEN);
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;
p1=p2;
p1=(struct student *)malloc(LEN);
scanf( "%ld,%f ",&p1-> num,&p1-> score);
}
p2-> next=NULL;
return(head);
}
void print(struct student *head)
{
struct student *p;
printf( "\nnow,these %d records are:\n ",n);
p=head;
if(head!=NULL)
do
{
printf( "%ld %5.1f\n ",p-> num,p-> score);
p=p-> next;

}while(p!=NULL);

}
main()
{
struct student *head;
head=creat();
printf( "%d ",n);
print(head);
return 0;
}

这个程序算法有错误 主要是全局变量 因为执行print函数的时候n就是0了
该怎么改一下 才能实现我的目的呢?

[解决办法]
#include <stdio.h>
#include <stdlib.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 *p1,*p2;
struct student *head;

n = 0;

p1 = p2 = (struct student *)malloc(LEN);

scanf( "%ld,%f ",&p1-> num, &p1-> score);
head = NULL;
while (p1-> num != 0)
{
n = n + 1;
if (n == 1)
{
head = p1;
head-> next = p2;
p2-> next =NULL;
}
else
{
p2-> next = p1;
p2=p2-> next;
p2-> next = NULL;
}

p1=(struct student *)malloc(LEN);
scanf( "%ld,%f ",&p1-> num,&p1-> score);
}

return(head);
}

void print(struct student *head)
{
struct student *p;
printf( "\nnow,these %d records are:\n ",n);
p = head;
if(head != NULL)
do
{
printf( "%ld,%5.1f\n ",p-> num,p-> score);
p = p-> next;
}while(p != NULL);

}

main()
{
struct student *head;
head = creat();
printf( "%d ",n);
print(head);
return 0;
}

我已经给你写好了
你之家看看

读书人网 >C语言

热点推荐