链表输入n个学生成绩,删除最高成绩,删除最低成绩,计算平均值代码
时间: 2024-09-09 13:01:04 浏览: 81
首先,我们需要定义链表的节点结构以及链表的基本操作,包括插入、删除和计算平均值的函数。下面是一个简单的Python代码示例,实现插入学生成绩到链表、删除最高成绩、删除最低成绩以及计算平均值的功能:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insert_scores(head, scores):
# 创建一个哨兵节点作为链表的起始节点
sentinel = ListNode()
current = sentinel
for score in scores:
current.next = ListNode(score)
current = current.next
# 更新头节点为实际的第一个节点
head = sentinel.next
return head
def delete_max(head):
if not head:
return None
if not head.next:
return None
# 最大值节点和前驱节点初始化
max_node = head
prev_max = None
current = head.next
current_prev = head
while current:
if current.val > max_node.val:
max_node = current
prev_max = current_prev
current_prev = current
current = current.next
# 删除最大值节点
prev_max.next = max_node.next
return head
def delete_min(head):
if not head:
return None
if not head.next:
return None
# 最小值节点和前驱节点初始化
min_node = head
prev_min = None
current = head.next
current_prev = head
while current:
if current.val < min_node.val:
min_node = current
prev_min = current_prev
current_prev = current
current = current.next
# 删除最小值节点
prev_min.next = min_node.next
return head
def calculate_average(head):
if not head:
return 0
total = 0
count = 0
current = head
while current:
total += current.val
count += 1
current = current.next
return total / count if count else 0
# 使用示例
scores = [70, 80, 90, 100, 50]
head = None
head = insert_scores(head, scores)
head = delete_max(head)
head = delete_min(head)
average = calculate_average(head)
print(f"删除最高和最低成绩后的平均分是: {average}")
```
这段代码中,我们首先定义了一个链表节点类`ListNode`,然后定义了`insert_scores`函数用于将成绩插入到链表中,`delete_max`和`delete_min`函数用于删除链表中的最高和最低成绩节点,`calculate_average`函数用于计算链表中所有成绩的平均值。
阅读全文