单链表将文件中的学生加权成绩按照加权成绩递增排序 代码
时间: 2024-12-19 16:27:57 浏览: 8
在Python中,我们可以使用内置的`heapq`模块,它提供了一个优先队列(堆),非常适合解决这种按值排序的问题。假设有一个单链表结构,其中包含学生的姓名和加权成绩,我们可以创建一个节点类(如`Node`)并定义一个链表类(如`WeightedGradeList`)。首先,我们将链表元素插入到最小堆中,然后逐出堆顶元素并调整链表顺序。
```python
import heapq
class Node:
def __init__(self, name, weighted_score):
self.name = name
self.weighted_score = weighted_score
self.next = None
class WeightedGradeList:
def __init__(self):
self.head = None
self.min_heap = []
def insert(self, node):
if not self.head:
self.head = node
heapq.heappush(self.min_heap, (node.weighted_score, node))
else:
if node.weighted_score > self.min_heap[0][0]:
self.min_heap[0] = (node.weighted_score, node)
heapq.heapify(self.min_heap)
else:
current = self.head
while current.next and node.weighted_score >= current.next.weighted_score:
current = current.next
node.next = current.next
current.next = node
# 添加所有学生数据后调用这个方法进行排序
def sort_by_weighted_score(self, students):
for student in students:
self.insert(student)
# 返回按加权成绩升序排列的学生列表
def get_sorted_list(self):
sorted_list = []
while self.min_heap:
_, node = heapq.heappop(self.min_heap)
sorted_list.append(node)
return sorted_list[::-1] # 因为heapq返回的是降序,所以需要反转
# 示例用法
students = [Node('Alice', 85), Node('Bob', 92), Node('Charlie', 78)]
grade_list = WeightedGradeList()
grade_list.sort_by_weighted_score(students)
sorted_students = grade_list.get_sorted_list()
for student in sorted_students:
print(f"{student.name}: {student.weighted_score}")
```
阅读全文