一個連結串列插入函式用到極致的演算法
阿新 • • 發佈:2018-12-13
這個連結串列結點插入的函式,會自動根據編號大小而有順序的插入其中(從大到小),不用像我的連結串列版課程設計一樣繁瑣的從頭部插入然後再根據編號的大小來排序,可以節省很多的程式碼量。也就是說按某個設定的順序插入,不是像我之前那樣,從首結點插入,然後再給結點排序,繁瑣,這樣更加簡便。
#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; }