用Python实现:假设一个班学生信息包括学号、姓名、成绩,用单链表实现对一个班的学生信息的录入、显示、查询、修改、插入、删除和按总分排名次等功能
时间: 2023-10-20 17:13:12 浏览: 174
以下是一个基本的单链表实现,其中每个节点表示一个学生信息:
```python
class StudentNode:
def __init__(self, id, name, score):
self.id = id
self.name = name
self.score = score
self.next = None
class StudentList:
def __init__(self):
self.head = None
def add(self, node):
if not self.head:
self.head = node
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = node
def display(self):
curr = self.head
while curr:
print(f"{curr.id}\t{curr.name}\t{curr.score}")
curr = curr.next
def search(self, id):
curr = self.head
while curr:
if curr.id == id:
return curr
curr = curr.next
return None
def update(self, id, name, score):
node = self.search(id)
if node:
node.name = name
node.score = score
def insert(self, index, node):
if index == 0:
node.next = self.head
self.head = node
else:
curr = self.head
while index > 1 and curr:
curr = curr.next
index -= 1
if curr:
node.next = curr.next
curr.next = node
else:
self.add(node)
def delete(self, id):
if not self.head:
return
if self.head.id == id:
self.head = self.head.next
else:
curr = self.head
while curr.next and curr.next.id != id:
curr = curr.next
if curr.next:
curr.next = curr.next.next
def sort_by_score(self):
nodes = []
curr = self.head
while curr:
nodes.append(curr)
curr = curr.next
nodes.sort(key=lambda node: node.score, reverse=True)
self.head = None
for node in nodes:
self.add(node)
```
然后我们可以使用这个链表来实现各种功能。例如,录入学生信息:
```python
students = StudentList()
students.add(StudentNode(1, 'Tom', 90))
students.add(StudentNode(2, 'Jerry', 80))
students.add(StudentNode(3, 'Alice', 95))
students.add(StudentNode(4, 'Bob', 85))
```
显示学生信息:
```python
students.display()
```
查询学生信息:
```python
node = students.search(3)
if node:
print(f"{node.id}\t{node.name}\t{node.score}")
else:
print("Student not found.")
```
修改学生信息:
```python
students.update(2, 'Jerry Mouse', 85)
```
插入学生信息:
```python
students.insert(2, StudentNode(5, 'Eva', 92))
```
删除学生信息:
```python
students.delete(1)
```
按总分排序:
```python
students.sort_by_score()
```
阅读全文