一个程序来实现动态链表的插入

#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; 
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_嘉木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值