python双向链表管理班级学生(学号 姓名 电话)
时间: 2024-10-22 21:23:09 浏览: 29
在Python中,我们可以使用双向链表来管理班级的学生信息,每个节点可以存储学生的学号、姓名和电话。首先,我们需要定义一个Node类,用于表示链表中的一个元素:
```python
class StudentNode:
def __init__(self, student_id, name, phone):
self.student_id = student_id
self.name = name
self.phone = phone
self.prev = None # 上一个节点
self.next = None # 下一个节点
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
# 插入学生节点
def insert_student(self, student_id, name, phone):
new_node = StudentNode(student_id, name, phone)
if not self.head:
self.head = self.tail = new_node
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
# 删除学生节点
def delete_student(self, student_id):
current = self.head
while current:
if current.student_id == student_id:
if current.prev:
current.prev.next = current.next
elif self.head == current:
self.head = current.next
if current.next:
current.next.prev = current.prev
else:
self.tail = current.prev
return True
current = current.next
return False
# 查找学生节点
def find_student(self, student_id):
current = self.head
while current:
if current.student_id == student_id:
return current
current = current.next
return None
# 示例操作
dll = DoublyLinkedList()
dll.insert_student(001, "张三", "123456789")
dll.insert_student(002, "李四", "234567890")
# 查找和删除操作...
```
阅读全文