#include<stdio.h>
#include<malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student//定义结构体
{long num;
float score;
struct student *next;
};
int n;
struct student *creat(void)//建立链表
{struct student *head;//定义结构体类型指针head,p1,p2
struct student *p1,*p2;
n=0;//定义结点长度n
p1=p2=(struct student *)malloc(LEN);//给p1,p2开辟相同的空间
scanf("%ld,%f",&p1->num,&p1->score);
while(p1->num!=0)
{n=n+1;
if(n==1)head=p1;//给表头赋值
else p2->next=p1;//把输入的数连在后面
p2=p1;
p1=(struct student *)malloc(LEN);//重新给P1开辟空间
scanf("%ld,%f",&p1->num,&p1->score);
}
p2->next=NULL;//把表尾设为0
return head;
}
void print(struct student *head)//输出链表
{struct student *p;
printf("\nNow,These %d records are:\n",n);
p=head;
if(head!=NULL)
do{
printf("%ld %5.1f\n",p->num,p->score);
p=p->next;//每输出一轮数据,就把指针指到下一个结点
}while(p!=NULL);
}
struct student *del(struct student *head,long num)//删除结点
{struct student *p1,*p2;
if(head==NULL){printf("\nlist null!\n");return head;}
p1=head;//把表头付给p1
while(num!=p1->num&&p1->next!=NULL)
{p2=p1;p1=p1->next;}//结点的轮换
if(num==p1->num)
{if(p1==head)head=p1->next;//如果输入的是表头
else p2->next=p1->next;//n+1的结点与n-1的结点相连
printf("delete:%d\n",num);
n=n-1;
}
else printf("%ld not been fould!\n",num);
return head;
}
struct student * insert(struct *head,struct student *stud)//结点的插入
{struct student *p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL)
{head=p0;p0->next=NULL;}
else
{while(p0->num>p1->num&&p1->next!=NULL)
{p2=p1;
p1=p1->next;}
if(p0->num<=p1->num)/*判断要插入的位置*/
{if(head==p1)head==p0;//如果为表头则直接接入
else p2->next=p0;
p0->next=p1;}
else
{p1->next=p0;p0->next=NULL;}
}
/*插入功能的缺点:无法再本来的两个数之间插入一个如102与103之间则无法进行*/
n=n+1;
return head;
}
main()//主函数
{struct student *head;
struct student *stu;
long del_num;
printf("input record:\n");
head=creat();
print(head);
printf("\ninput the deleted number:");
scanf("%ld",&del_num);
while(del_num!=0)
{head=del(head,del_num);
print(head);
printf("input the insert record:");
scanf("%ld",&del_num);}
printf("\ninput the inserted record:");
stu=(struct student *)malloc(LEN);
scanf("%ld,%f",&stu->num,&stu->score);
while(stu->num!=0)
{head=insert(head,stu);
print(head);
printf("input the inserted record:");
stu=(struct student *)malloc(LEN);
scanf("%ld,%f",&stu->num,&stu->score);
}
}把输出的代码改下就好了