#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student *creat();
struct student *del(struct student *head,int num);
int print(struct student *head);
//******************************************//
int n;
//******************************************//
struct student
{
int num;
float score;
struct student *next;
};
//******************************************//
int main()
{
struct student *p,*stu;
int num;
stu=creat();
p=stu;
print(p);
do
{
printf("Please input the num to deleat:");
scanf("%d",&num);
print(del(p,num));
}while(num!=0);
printf("\n\n");
system("pause");
}
//******************************************//
struct student *creat()
{
struct student *head,*p1,*p2;
p1=p2=(struct student*) malloc(LEN);
printf("input the num: ");
scanf("%d",&p1->num);
printf("input the score: ");
scanf("%f",&p1->score);
head=NULL;
n=0;
while(p1->num!=0)
{
n++;
if(n==1)
{
head=p1;
//head指向p1
}
else
{
p2->next=p1;
//p2指向p1
}
p2=p1;
//除去p1,让p2代替p1
p1=(struct student *)malloc(LEN);
//重新输入一个p1
printf("input the num: ");
scanf("%d",&p1->num);
printf("input the score: ");
scanf("%f",&p1->score);
}
p2->next=NULL;
//p1
return head;
}
//******************************************//
int print(struct student *head)
{
struct student *p;
printf("There are %d records\n",n);
printf("\t\tnumber\t\tscore\n");
p=head;
while(p!=NULL)
{
printf("\t\t%d\t\t%.2f\n",p->num,p->score);
p=p->next;
}
}
//******************************************//
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("\nThis list is null!\n");
goto END;
}
p1=head;
//为什么这里是p1指向head而不是head指向p1
while(p1!=NULL)
{
//
if(p1->num==num)
{
if(p1==head)
{
head=p1->next;
free(p1);
p1=head->next;
}
else
{
p2->next=p1->next;
free(p1);
p1=p2->next;
}
printf("\nDeleat NO:%d succesed!\n",num);
n=n-1;
}
else
{
p2=p1;
p1=p1->next;
}
}
END:
return(head);
}
试试是不是你想要的。