链表删除求教,自己写的代码,劳驾各位前辈看看哪里出错了
本帖最后由 anjsy6 于 2013-03-12 16:39:16 编辑
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct stu *creat();
void print(struct stu *q);
struct stu *del(struct stu *d);
struct stu
{
int num;
float score;
struct stu *next;
};
int n;
void main()
{
struct stu *p,*p1;
p=creat();
printf("学生的学号和成绩如下:\n");
print(p);
p1=del(p);
print(p1);
system("pause");
}
struct stu *creat(struct stu *head)
{
struct stu *p1,*p2;
n=0;
head=NULL;
p1=p2=(struct stu *)malloc(sizeof(struct stu));
printf("请输入学生学号:\n");
scanf("%d",&p1->num);
printf("请输入该生成绩:\n");
scanf("%f",&p1->score);
while(p1->num)
{
n++;
if(n==1) head=p1;
p1=(struct stu *)malloc(sizeof(struct stu));
printf("请输入学生学号:\n");
scanf("%d",&p1->num);
printf("请输入该生成绩:\n");
scanf("%f",&p1->score);
p2->next=p1;
p2=p1;
if(p1->num==0) p2->next=NULL;
}
return head;
}
void print(struct stu *q)
{
struct stu *q1;
q1=q;
if(q!=NULL)
{
do
{
printf("学号:%d\t成绩:%.2f\t\n",q1->num,q1->score);
q1=q1->next;
}while(q1->next!=NULL);
}
}
struct stu *del(struct stu *d)
{
struct stu *d1,*d2;
int num;
d1=d;
printf("请输入要删除的学生的学号:\n");
scanf("%d",&num);
if(d!=NULL)
{
do
{
if(num!=d1->num) d1=d1->next;
else
{
d2=d1;
d1=d1->next;
d2->next=d1;
}
}while(d2->next==d1);
}
return d;
}
struct stu *del(struct stu *d)
{
struct stu *d1,*d2;
int num;
d1=d;
printf("请输入要删除的学生的学号:\n");
scanf("%d",&num);
if(d!=NULL)
{
do
{
if(num!=d1->num) d1=d1->next;
else
{
d2=d1;
d1=d1->next;
d2->next=d1;
}
}while(d2->next==d1);//d2没有初值,如果num!=d1->num成立 判断d2->next==d1时就产生错误了
}
return d;
}