c语言链表输入n个学生成绩,删除最高成绩,删除最低成绩,计算平均值代码
时间: 2024-09-08 07:02:15 浏览: 99
在C语言中,操作链表来输入学生成绩,删除最高和最低成绩,并计算平均值可以分为以下几个步骤:
1. 定义链表节点结构体,包含成绩和指向下一个节点的指针。
2. 创建链表,根据输入的学生成绩初始化链表节点。
3. 遍历链表找到最高成绩和最低成绩的节点。
4. 删除最高成绩和最低成绩的节点。
5. 遍历链表计算所有成绩的总和。
6. 计算平均值,即总和除以学生数量。
以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int score;
struct Node *next;
} Node;
Node* createNode(int score) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->score = score;
newNode->next = NULL;
return newNode;
}
Node* insertNode(Node *head, int score) {
Node *newNode = createNode(score);
if (head == NULL || head->score < newNode->score) {
newNode->next = head;
head = newNode;
} else {
Node *current = head;
while (current->next != NULL && current->next->score < newNode->score) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
return head;
}
void deleteMax(Node **head) {
if (*head == NULL || (*head)->next == NULL) return;
Node *current = *head;
Node *maxPrev = NULL;
while (current->next != NULL) {
if (current->next->score > current->score) {
maxPrev = current;
current = current->next;
} else {
current = current->next;
}
}
if (maxPrev == NULL) {
*head = (*head)->next;
} else {
maxPrev->next = maxPrev->next->next;
}
free(current);
}
void deleteMin(Node **head) {
if (*head == NULL || (*head)->next == NULL) return;
Node *minPrev = *head;
Node *current = (*head)->next;
while (current->next != NULL) {
if (current->next->score < minPrev->next->score) {
minPrev = current;
current = current->next;
} else {
current = current->next;
}
}
if (minPrev->next == *head) {
*head = (*head)->next;
} else {
minPrev->next = minPrev->next->next;
}
free(current);
}
float calculateAverage(Node *head) {
int total = 0;
int count = 0;
Node *current = head;
while (current != NULL) {
total += current->score;
count++;
current = current->next;
}
if (count == 0) return 0.0;
return (float)total / count;
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->score);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
int n, score;
printf("请输入学生成绩的个数: ");
scanf("%d", &n);
printf("请输入学生成绩: ");
for (int i = 0; i < n; i++) {
scanf("%d", &score);
head = insertNode(head, score);
}
printf("原始成绩列表: ");
printList(head);
deleteMax(&head);
printf("删除最高成绩后的列表: ");
printList(head);
deleteMin(&head);
printf("删除最低成绩后的列表: ");
printList(head);
float average = calculateAverage(head);
printf("平均成绩: %.2f\n", average);
// 释放链表内存
while (head != NULL) {
Node *temp = head;
head = head->next;
free(temp);
}
return 0;
}
```
阅读全文