//头文件预处理部分
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct student)
//函数体的创建,需要放到主函数的前面,不然会报错
struct student
{
int num;
char name[10];
float score;
struct student *next;
};
//声明函数部分
struct student *create(); //链表创建
void print(struct student *head);//链表输出打印
struct student *insert(struct student *head,struct student *stu_x);//链表插入结点
//主函数部分,程序的入口
int main()
{
struct student *stu;
stu=create();
print(stu);
printf("请输入需要插入的学生的学号,姓名,成绩:");
printf("\n");
struct student stu_x; //重新定义一个需要插入的"结点"stu_x,类型为struct student
scanf("%d %s %f",&stu_x.num,&stu_x.name,&stu_x.score );//"stu_x.num"表示结构体stu_x中的成员num
struct student *stu_insert;
stu_insert=insert(stu,&stu_x);
print(stu_insert);
return 0;
}
int n; //全局变量
//链表的创建
struct student *create()
{
struct student *p1,*p2;
struct student *head;
p1=(struct student *)malloc(LEN);
head=NULL;
n=0;
printf("请输入学生的学号,姓名,分数:\n");
scanf("%d %s %f",&p1->num ,&p1->name,&p1->score );
while(p1->num !=0)
{
n++;
if(n==1)
{
head=p1;
}
else
{
p2->next =p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%d %s %f",&p1->num ,&p1->name,&p1->score );
}
p2->next =NULL;
return head;
}
void print(struct student *head)//无返回值,所以类型为"void"类型
{
struct student *p;
p=head;
printf(" 所有学生信息如下:\n");
printf("-------------------\n");
printf(" 学号 | 姓名 | 分数\n");
if(head!=NULL)
{
do
{
printf(" %2d %4s %2.2f\n",p->num,p->name,p->score);
p=p->next ;
}while(p!=NULL);
}
}
//插入结点
struct student *insert(struct student *head,struct student *stu_x)//定义插入结点的函数,
//返回值为head(头指针,指向链表的首地址),
//所以函数类型为"struct student *"类型
{
struct student *p1,*p2;
p1=head;
struct student *p_x;
p_x=stu_x;
if(head==NULL)//判断是否为原来的空链表是否为空
{
head=p_x;
p_x->next =NULL;
}
else
{
while((p_x->num >p1->num)&&p1->next!=NULL)
{
p2=p1;
p1=p1->next ;
}
if(p_x->num <p1->num)
{
if(p1==head)
{
head=p_x;
p_x->next=p1;
}
else
{
p2->next =p_x;
p_x->next=p1;
}
}
else //即p1==NULL
{
p1->next =p_x;
p_x=NULL;
}
}
n=n+1;//全局变量的作用体现
return head;
}
05-26
263