|
3鱼币
经单步调试发现,问题出在了如下删除结点的函数里,比如我输入学号5,成绩90,学号4,成绩80,学号3,成绩80这样,删除的学号输入4,下面函数中 if(p1=head) 总是为真,因为if(p1->num==a)判断是成立的,就是说此时的p1已经是下个结点了,而不是head,但是 if(p1=head) 却是真的,在运行的结果就是,无论输入5,4,3,最后都会删除第一个人的成绩与学号,小弟百思不得其解,来几位朋友帮帮忙,谢谢!!!!!!!!!!!!!!!!!!!!
p1=head;
while( p1->num != a && p1->next != NULL )
{
p2=p1;
p1=p1->next;
}
if(p1->num==a)
{
if(p1=head)
{
head=p1->next;
return head;
}
else
p2->next=p1->next;
return head;
}
else
{
printf("找不到学号\n");
return head;
}
————————————————————————————————————————————————
————————————————————————————————————————————-———
以下是全程序:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define CD sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
void main()
{
struct student *creat();
struct student *del();
void print(struct student *head);
struct student *stu;
stu=creat();
print(stu);
stu=del(stu);
print(stu);
}
struct student *creat()
{
struct student *p1,*p2, *head;
p1=p2=(struct student*)malloc(CD);
printf("输入学号:");
scanf("%d",&p1->num);
printf("输入成绩:");
scanf("%f",&p1->score);
head=NULL;
n=0;
while(p1->num != 0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student*)malloc(CD);
printf("输入学号:");
scanf("%d",&p1->num);
printf("输入成绩:");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
}
struct student *del(struct student *head)
{
long a;
struct student *p1,*p2;
printf("请输入你要删除的学号:\n");
scanf("%d",&a);
if(head==NULL)
{
printf("这个是空表\n");
return head;
}
p1=head;
while( p1->num != a && p1->next != NULL )
{
p2=p1;
p1=p1->next;
}
if(p1->num==a)
{
if(p1=head)
{
head=p1->next;
return head;
}
else
p2->next=p1->next;
return head;
}
else
{
printf("找不到学号思密达\n");
return head;
}
}
void print(struct student *head)
{
struct student *p;
printf("\nThere are %d records!\n\n", n);
p = head;
if( head )
{
do
{
printf("学号为 %d 的成绩是: %f\n", p->num, p->score);
p = p->next;
}while( p );
}
}
|
|