#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n;
struct Student *creat()
{
struct Student *p1,*p2,*head;
n=0;head=NULL;
p1=p2=(struct Student *)malloc(LEN);
printf("Input the num:");
scanf("%d",&p1->num );
printf("Input the score:");
scanf("%f",&p1->score );
while(p1->num)
{
n++;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct Student *)malloc(LEN);
printf("Input the num:");
scanf("%d",&p1->num );
printf("Input the score:");
scanf("%f",&p1->score );
}
p2->next =NULL;
return head;
}
struct Student *insert(struct Student *head,struct Student *stu_2)//链表的插入
{
struct Student *p1,*p2,*p0;
p1=head;
p0=stu_2;
if(head==NULL)
{
head=p0;
p0->next =NULL;
}
else
{
while((p0->num >p1->num )&&p1->num !=NULL)//达到插入的条件,即前面(学号)比他小后面比他大
{
p2=p1;
p1=p1->next ;
}
if(p0->num <=p1->num )
{
if(head==p1)//p1是头结点,插入头部
{
head=p0;
}
else //一般情况,插入中间
{
p2->next =p0;
}
p0->next =p1;
}
else
{
p1->next =p0;
p0->next =NULL;
}
}
n++;
return head;
}
void print(struct Student *head)
{
struct Student *p;
p=head;
if(head)
{
do{
printf("number:%d\tscore:%.2f\n",p->num ,p->score );
p=p->next ;
}while(p);
}
}
int main()
{
struct Student *stu,*p,stu_2;
stu=creat();
p=stu;
print(p);
printf("Please input the num to insert:\n");
scanf("%d",&stu_2.num);
printf("Please input the score:\n");
scanf("%f",&stu_2.score );
p=insert(stu,&stu_2);
print(p);
system("pause");
return 0;
}
一个程序来实现动态链表的插入
本文介绍了一段C语言代码,实现了一个学生信息结构的链表,包括节点创建、插入新节点和打印链表功能。通过实例展示了如何使用`creat()`函数创建链表,`insert()`函数插入节点,以及`print()`函数遍历并显示链表内容。
摘要由CSDN通过智能技术生成