c语言编程题,程序功能: 建立一个链表,每个结点包括:学号、姓名、性别、年龄,输入一个学号,如果链表中

#include "stdio.h"
#include "malloc.h"
#define NULL 0
#define LEN sizeof(struct student)
struct student
{
long num;
char name[10];
char sex[3];
int age;
struct student *next;
};
int n;
struct student *creat(int a)
{
struct student *head;
struct student *p1,*p2;
head=NULL;
while(n=0;n<a;n++)
{p1=(struct student*)malloc(LEN);
scanf("%ld,%s,%s,%d",&p1->num,p1->name,p1->sex,&p1->age);
if(n==0) head=p1;
else p2->next=p1;
p2=p1;
}
p1->next=NULL;
return(head);
}
void main()
{
struct student *p1,*head,*p2;
int n;
long t;
printf("please input the total number");
scanf("%d",&n);
head=p1=p2=creat(n);
printf("please input the num you want to delete");
scanf("%ld",&t);
while(t!=p1->num&&p1!=NULL){ p2=p1;p1=p1->next;}
if(p1==NULL) printf("the num you want to delete is not exist");
else
{
printf("%ld,\n%s,\n%s,\n%d\n",p1->num,p1->name,p1->sex,p1->age);
if(p1==head) head=p1->next;
else if(p1->next==NULL) p2->next=NULL;
else p2->next=p1->next;
}
}
我编的程序如上,可是系统老提示出错,哪位大侠帮我看一下

struct student *creat(int a)
{
struct student *head;
struct student *p1,*p2;
head=NULL;
for(n=0;n<a;n++) //这里改成for
{
p1=(struct student*)malloc(LEN);
scanf("%ld %s %s %d",&p1->num,p1->name,p1->sex,&p1->age); //这里改成空格才可以保证name sex正确输入!!
if(n==0) head=p1;
else p2->next=p1;
p2=p1;
}
p1->next=NULL;
return(head);
}

int main()
{
struct student *p1,*head,*p2;
int n;
long t;
printf("please input the total number");
scanf("%d",&n);
head=p1=p2=creat(n);
printf("please input the num you want to delete");
scanf("%ld",&t);

//while(t!=p1->num&&p1!=NULL){ p2=p1;p1=p1->next;}
while( p1!=NULL && t!=p1->num){ p2=p1;p1=p1->next;} //要先判断p1是否为空,再判断数据是否相同,否则找不到数据时会出错
if(p1==NULL) printf("the num you want to delete is not exist");
else
{
printf("%ld,\n%s,\n%s,\n%d\n",p1->num,p1->name,p1->sex,p1->age);
if(p1==head) head=p1->next;
/**以下两句是废话**
else if(p1->next==NULL) p2->next=NULL;
else p2->next=p1->next;
****/
p2->next=p1->next;
free(p1); //删除了,就释放掉这个结点
}

//显示一下 剩余的数据
printf("\n" );
p1=head;
while ( p1 )
{
printf("%ld, %s, %s, %d\n",p1->num,p1->name,p1->sex,p1->age);
p1=p1->next;
}
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-24
struct student *creat(int a)
{
struct student *head;
struct student *p1,*p2;
head=NULL;
while(n=0;n<a;n++) //这一行出错了,while应改为for
{p1=(struct student*)malloc(LEN);
scanf("%ld,%s,%s,%d",&p1->num,p1->name,p1->sex,&p1->age);
if(n==0) head=p1;
else p2->next=p1;
p2=p1;
}
相似回答