C语言单链表练习,插入/删除/查找最大最小值/求平均值

  • Post author:
  • Post category:其他


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct student)

struct student

{
	long num;
	float score;
	struct student* next;
};
int n;

struct student* creat(void)
{
	struct student* p1, *p2;
	struct student* head;
	n = 0;
	head = p1 = (struct student*)malloc(LEN);
	p2 = (struct student*)malloc(LEN);
	scanf_s("%ld,%f", &p2->num, &p2->score);
	while (p2->num != 0)
	{
		n = n + 1;
		p1->next = p2;
		p1 = p2;
		p2 = (struct student*)malloc(LEN);
		scanf_s("%ld,%f", &p2->num, &p2->score);
	}
	p1->next = NULL;
	return (head);

}
void sc(struct student* head)
{
	struct student* p;
	printf_s("\n成绩是:\n", n);
	p = head->next;
	while (p != NULL)
	{
		printf("%ld%5.1f\n", p->num, p->score);
		p = p->next;
	}
}

struct student* del(struct student* head, long num)
	//在此处完成删除函数操作
{
	struct student* p, *q;
	p = head;
	while (p->next)
	{
		if (p->next->num != num) {
			p = p->next;
		}
		else
		{
			q = p->next;
			p->next = p->next->next;
			free(q);
			break;
		}
	}
	return(head);
}

struct student* insert(struct student* head, struct student* stud)
	//在此处完成插入函数操作
{

	stud->next = head->next;
	head->next = stud;
	return(head);

}


int max_min_ave(struct student *head)
//在此处完成求最高成绩、最低成绩、平均成绩的函数操作
{
	//最高成绩
	struct student*p, *q, *s;
	p = head->next;
	float max = p->score;
	q = head->next;
	float min = p->score;
	s = head->next;
	float sum = 0;
	int n = 0;
	while (p->next)
	{
		p = p->next;
		if (p->score > max)
		{
			max = p->score;
		}
		if (p->score < min)
		{
			min = p->score;
		}
	}
	while (s)
	{
		sum = sum + s->score;
		n++;
		s = s->next;
	}
	float ave = sum / n;
	printf("最高成绩:%f,最低成绩:%f,平均成绩:%f", max, min, ave);

	return(head);
}

void main()
{
	struct student* head, *stu;

	long del_num;

	printf("输入数:\n");
	head = creat();
	sc(head);

	printf("输入需要删除的学号:\n");
	scanf_s("%ld", &del_num);


	//在此处调用删除函数,完成连续删除操作,并调用sc(head)输出链表
	while (del_num != 0) {
		del(head, del_num);
		printf("输入需要删除的学号:\n");
		scanf_s("%ld", &del_num);
	}
	sc(head);


	printf("输入需要插入的学号和成绩\n");
	stu = (struct student*)malloc(LEN);
	scanf_s("%ld,%f", &stu->num, &stu->score);


	//在此处调用插入函数,完成连续插入操作,并调用sc(head)输出链表
	while (stu->num != 0) {
		insert(head, stu);
		printf("输入需要插入的学号和成绩\n");
		stu = (struct student*)malloc(LEN);
		scanf_s("%ld,%f", &stu->num, &stu->score);
	}
	sc(head);

	//在此处调用求最高成绩、最低成绩、平均成绩的函数
	max_min_ave(head);
}

输入学号成绩时按照如下格式:0,0

输入0结束输入



版权声明:本文为weixin_45419957原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。