这个链表结点插入的函数,会自动根据编号大小而有顺序的插入其中(从大到小),不用像我的链表版课程设计一样繁琐的从头部插入然后再根据编号的大小来排序,可以节省很多的代码量。也就是说按某个设定的顺序插入,不是像我之前那样,从首结点插入,然后再给结点排序,繁琐,这样更加简便。
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
struct student *creat()
{
FILE *fp1;
fp1 = fopen("database.txt", "r");
struct student *head;
struct student *p1, *p2;
n = 0;
p1 = p2 = (struct student*)malloc(LEN);
fscanf(fp1,"%ld,%f", &p1->num, &p1->score);
head = NULL;
while (p1->num != 0)
{
n = n + 1;
if (n == 1) head = p1;
else p2->next = p1;
p2 = p1; //p1就是遍历的
p1 = (struct student*)malloc(LEN);
fscanf(fp1,"%ld,%f", &p1->num, &p1->score);
}
p2->next = NULL;
return (head);
fclose(fp1);
}
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 *insert(struct student *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; p0->next=p1; }
else {p2->next=p0; p0->next=p1; }
}
else {p1->next=p0; p0->next=NULL;} }
n=n+1;
return(head);
}
int main()
{
struct student *head,stu;
head = creat();
scanf("%ld,%f",&stu.num,&stu.score);
head=insert(head,&stu);
print(head);
system("pause");
return 0;
}