简单链表的创建与插入实现

//头文件预处理部分
#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值