5.20作业

5.20作业

要求写一个函数insert,用来向一个动态链表中插入结点。

#include <stdio.h>
#include <malloc.h>
//写一个函数insert,用来向一个动态链表中插入结点。
struct student//定义链表
{
	long num;
	float score;
	struct student *next;
};
struct student *creat()//创建动态链表
{ 
	struct student *head=NULL,*p1, *p2;
	int n=0;
	p1=p2=(struct student*)malloc(sizeof (struct student));
	scanf("%ld%f",&p1->num,&p1->score);
	while(p1->num!=0)
	{
		n=n+1;
		if (n==1) head=p1;
		else p2->next=p1;
		p2=p1;
		p1=(struct student *) malloc(sizeof (struct student));
		scanf("%ld%f",&p1->num,&p1->score);
	}
	p2->next=NULL;
	return (head);
}
struct student *insert(int j,student *head) //在第j处插入输入的数据
{
	int n,m;
	student *p=head;
	student *s=(student*)malloc(sizeof(student));
	printf("请输入num的值\n");
	scanf("%d", &n);
	s->num=n;
	printf("请输入score的值\n");
	scanf("%d", &m);
	s->score=m;
	for (int i=0;i<j-1;++i)
	{p=p->next;}
	s->next=p->next;
	p->next=s;
	return head;
}
void main()
{
	struct student *creat();
	struct student *insert(int m,student *head);
	student *head,*p;
	int i;
	head=creat();
	p=head;
	printf("输出未插入新节点前链表\n");
	while(p!=NULL)
	{
		printf("num:%ld score:%5.1f\n",p->num,p->score);
		p=p->next;
	}
	printf("请输入需要插入的位置\n");
	scanf("%d", &i);
	head=insert(i, head);
	p=head;
	printf("输出插入新节点后链表\n");
	while(p!=NULL)
	{
		printf("num:%ld score:%5.1f\n",p->num,p->score);
		p=p->next;
	}
}  
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值