一个链表插入函数用到极致的算法

本文介绍了一个链表结点插入函数,该函数能够根据编号大小自动将新结点插入到链表中,实现从大到小的有序排列,避免了繁琐的排序过程,简化了代码并提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个链表结点插入的函数,会自动根据编号大小而有顺序的插入其中(从大到小),不用像我的链表版课程设计一样繁琐的从头部插入然后再根据编号的大小来排序,可以节省很多的代码量。也就是说按某个设定的顺序插入,不是像我之前那样,从首结点插入,然后再给结点排序,繁琐,这样更加简便。

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值