使用链式结构建立学生信息表,实现建表,插入,删除和打印等基本功能
时间: 2024-12-08 08:16:09 浏览: 23
在数据库设计中,我们可以利用链式结构(如链表或树形数据结构)构建一个动态的学生信息表。首先,我们需要创建一个表示学生的基本结构体或类,包含学生的属性如姓名、学号、成绩等。然后,我们将这些实体通过指针链接起来,形成一个链表。
**1. 建表**:
```python
class Student:
def __init__(self, name, id, score):
self.name = name
self.id = id
self.score = score
self.next = None
# 创建一个空的链表头节点
head = None
```
**2. 插入**:
```python
def insert_student(self, student):
new_node = Student(student.name, student.id, student.score)
if not head:
head = new_node
else:
current = head
while current.next:
current = current.next
current.next = new_node
```
**3. 删除**:
```python
def delete_student_by_id(self, id):
if not head:
return
if head.id == id:
head = head.next
return
current = head
while current.next and current.next.id != id:
current = current.next
if current.next:
current.next = current.next.next
```
**4. 打印所有学生信息**:
```python
def print_students(self):
current = head
while current:
print(f"学生ID:{current.id}, 姓名:{current.name}, 成绩:{current.score}")
current = current.next
```
阅读全文