链表实现学生管理系统的设计与实现
一、系统概述
学生管理系统是一个用于管理学生信息的软件,包括学生的基本信息、成绩、考勤等。本系统采用链表数据结构来实现学生信息的存储和管理。
二、功能需求
1. 添加学生信息:输入学生的基本信息(如学号、姓名、性别、年龄等),将学生信息添加到链表中。
2. 删除学生信息:根据学号查找学生信息,将其从链表中删除。
3. 修改学生信息:根据学号查找学生信息,修改其基本信息。
4. 查询学生信息:根据学号查找学生信息,并显示其详细信息。
5. 显示所有学生信息:遍历链表,将所有学生信息输出。
6. 退出系统:结束程序运行。
三、设计思路
1. 定义一个链表节点类,包含学生的基本信息和指向下一个节点的指针。
2. 定义一个链表类,包含一个头节点,以及添加、删除、修改、查询和显示所有学生信息的方法。
3. 在链表类中,使用循环遍历链表,实现对学生信息的添加、删除、修改、查询和显示。
四、代码实现
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class StudentList:
def __init__(self):
self.head = None
def add(self, x):
if not self.head:
self.head = ListNode(x)
else:
current = self.head
while current.next:
current = current.next
current.next = ListNode(x)
def delete(self, key):
if self.head is None:
return
if self.head.val == key:
self.head = self.head.next
return
current = self.head
while current.next is not None:
if current.next.val == key:
current.next = current.next.next
return
current = current.next
def modify(self, key, new_val):
if self.head is None:
return
if self.head.val == key:
self.head = ListNode(new_val)
return
current = self.head
while current.next is not None:
if current.next.val == key:
current.next = ListNode(new_val)
return
current = current.next
def query(self, key):
if self.head is None:
return None
if self.head.val == key:
return self.head.next
current = self.head
while current.next is not None:
if current.next.val == key:
return current.next
current = current.next
return None
def display(self):
if self.head is None:
return
current = self.head
while current is not None:
print(current.val, end=' ')
current = current.next
print()
```
五、测试用例
```python
student_list = StudentList()
student_list.add(1)
student_list.add(2)
student_list.add(3)
student_list.display() # 输出:1 2 3
student_list.delete(2)
student_list.display() # 输出:1 3
student_list.modify(1, 4)
student_list.display() # 输出:1 4
student_list.query(2) # 输出:3
student_list.display() # 输出:1 4
```