编程实现下列函数,并将以下所有函数组织在一个C程序中:
(1).编写函数struct student *creat(void),
建立一个有n名学生数据的头指针为head的单向动态链表。
链表的结点类型为struct student,
如下所示: struct student //链表结点 { long num; //学号
int score; //分数 struct student //结点指针域 };
(2).编写函数struct student *insert(struct student *head),
从头指针为head的学生链表的表尾插入一个新的学生数据结点。
(3).编写函数 struct student *del(struct student *head, long key),
从头指针为head的学生链表中删除学号为key的那个结点。
(4). 编写函数 int sum(struct student *head),
返回头指针为head的学生链表中所有结点分数的和值。
(5). 编写函数 void find(struct student *head),
输出头指针为head的学生链表中分数最高的学生的学号和分数。
(6). 编写函数 void print(struct student *head),
输出头指针为head的学生链表中所有结点的内容。
实例输出情况:
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct student)
struct student
{
long num;
int score;
struct student *next;
};
int n;
struct student *creat(void)//creat()函数括号中是用来放参数的,void表示没有参数,可以不写
{
struct student*head;
struct student*p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);//(struct student*)是强制类型转换,
//因为malloc函数的返回值的void,即void *malloc(unsigned int size),即void *,
//而p1,p2是struct student*型,故应该用强制类型转换
scanf("%ld %d",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n++;
if(n==1)
head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%ld %d",&p1->num,&p1->score);
}
p2->next=NULL;
return(head);
}
struct student *insert(struct student *head,struct student *stu)//stu是要插入的地址
{
struct student *p0,*p1,*p2;
p1=head;
p0=stu;
if(head==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
while((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<p1->num)
{
if(head==p1) head=p0;
else p2->next=p0;
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
n=n+1;
return(head);
}
}
struct student *del(struct student *head,long key)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("\nlist null!\n");
return(head);
}
p1=head;
while(key!=p1->num&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(key==p1->num)
{
if(p1==head)
head=p1->next;
else p2->next=p1->next;
printf("delete:%ld\n",key);
n=n-1;
}
else printf("%ld not been found!\n",key);
return head;
}
int sum(struct student*head)
{
struct student *p;
int sum;
p=head;
if(head!=NULL)
do
{
sum+=p->score;
p=p->next;
}while(p!=NULL);
return sum;
}
void find(struct student*head)
{
struct student *p,*k;
struct student *max;
p=head;
max=head;
if(head!=NULL)
do
{
if(max->score<p->score)
{
max=p;
}
p=p->next;
}while(p!=NULL);
printf("分数最高的学生的信息是:\n");
printf("%ld %d\n",max->num,max->score);
}
void *print(struct student *head)
{
struct student *p;
printf("\nNow these %d records are:\n",n);
p=head;
if(head!=NULL)
do
{
printf("%ld %d\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
void main()
{
struct student *head;
struct student *stu;
long key;
struct student stud;
printf("请输入学生信息:\n");
head=creat();
printf("\n请输入你想删除的学生学号:\n");
scanf("%ld",&key);
head=del(head,key);
printf("\n请输入你想插入的学生的信息:\n");
scanf("%ld %d",&stud.num,&stud.score);
stu=&stud;
head=insert(head,stu);
print(head);
find(head);
printf("所有学生分数的和为:%d\n",sum(head));
}