- #include "stdio.h"
- #include "malloc.h"
- struct stu
- {
- int num;
- float score;
- struct stu *next;
- };
- struct stu *create()
- {
- int n;
- struct stu *head,*p1,*p2;
- head=NULL;
- p1=p2=(struct stu*)malloc(sizeof(struct stu));
- //注意p1和p2都要分配空间
- printf("please input:\\n");
- scanf("%d %f",&p1->num,&p1->score);
- n=0;
- while(p1->num!=0)
- {
- n++;
- if(n==1)
- head=p1;
- else {
- p2->next=p1;
- p2=p1;
- p1=(struct stu*)malloc(sizeof(struct stu));
- scanf("%d %f",&p1->num,&p1->score);
- }
- }
- p2->next=NULL;
- return head;
- }
- struct stu *insert(struct stu *head,struct stu *stud)
- {
- struct stu *p0,*p1,*p2;
- p1=head;
- p2=p1;
- p0=stud;
- if(NULL==head){head=p0;p0->next=NULL;}
- else
- {
- while((p0->num>p2->num)&&(p1->next!=NULL))
- {
- p2=p1;
- p1=p1->next;
- }
- if(p0->num<p1->num)
- {
- if(head==p1)head=p0;
- else
- {
- p0->next=p1;
- p2->next=p0;
- }
- }
- else
- {
- p1->next=p0;
- p0->next=NULL;
- }
- }
- return head;
- }
- struct stu *print(struct stu *head)
- {
- struct stu*p;
- p=head;
- while(p)
- {
- printf("%d %f\\n",p->num,p->score);
- p=p->next;
- }
- }
- void main()
- {
- struct stu *create();
- struct stu *insert(struct stu *head ,struct stu *stud);
- struct stu *head,*p1,*p2;
- head=create();
- p1=head;
- print(p1);
- p2=(struct stu*)malloc(sizeof(struct stu));
- printf("please input inserted number:\\n");
- scanf("%d %f",&p2->num,&p2->score);
- p1=insert(head,p2);
- print(p1);
- }
- //该片段来自于http://www.codesnippet.cn/detail/020720149903.html
来源: http://www.codesnippet.cn/detail/020720149903.html