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