Ja5oN 发表于 2007-1-10 21:13

可以帮我优化一下这段代码吗?

我想用一个函数完成学生信息的录入。可以调用一次函数输入多组数据
以下是我的代码

struct student
{
char num;char name;float eng,math,cpro;struct student*next,*pre;
};
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define L sizeof(struct student)
#define NULL 0
struct student*head ,*tail;
int count=0;\\学生个数

void input(void)
{
struct student*p;
printf ("请输入学生的信息,依次为学号、姓名、英语成绩、数学成绩、c语言成绩。以学号0结束输入\n");
do
{
p=(struct student*)malloc(L);
scanf("%s%s%f%f%f",p->num,p->name,&p->eng,&p->math,&p->cpro);
count++;
if (count==1) {head=p;tail=p;p->next=NULL;p->pre=NULL;}
else
{
   tail->next=p;p->pre=tail;p->next=NULL;tail=p;
}
}
while(strcmp(p->num,"0")!=0);
tail=tail->pre;   
tail->next=NULL;
free(p);
}

由于我用的是do……while循环,所以每次调用函数输入结束后都有一个学号为0的空节点;所以每次调用函数都会多申请一个节点然后把它释放,效率很低。
但是用while循环,第一次输入时又不能判断
请问有什么好的方法吗?

小I 发表于 2007-1-10 22:03

你可以在While之前做一次scanf呀

Ja5oN 发表于 2007-1-10 22:06

哦!明白了!谢谢,一时脑塞没想到!!
谢谢!!
页: [1]
查看完整版本: 可以帮我优化一下这段代码吗?