python双向链表管理学生数据(学号 姓名 电话)
时间: 2024-10-17 22:09:04 浏览: 20
python双向链表实现实例代码
5星 · 资源好评率100%
Python 中可以使用双向链表结构来管理学生数据,比如学号、姓名和电话。双向链表的特点是可以从前往后和从后往前遍历,非常适合动态添加或删除元素。下面是一个简单的示例,展示了如何创建一个节点类和双向链表类来存储和操作学生的数据:
```python
class Node:
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 StudentLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, student_data):
new_node = Node(*student_data)
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 get_student_by_id(self, id):
current = self.head
while current and current.student_id != id:
current = current.next
return current
def delete_by_id(self, id):
current = self.head
if current and current.student_id == id:
self.head = current.next
if current.next:
current.next.prev = None
else:
prev = None
while current and current.student_id != id:
prev = current
current = current.next
if current:
prev.next = current.next
if current.next:
current.next.prev = prev
# 使用示例
students_list = StudentLinkedList()
students_list.append((1001, '张三', '13812345678'))
students_list.append((1002, '李四', '13987654321'))
# 查找特定学生
node = students_list.get_student_by_id(1002)
if node:
print(f"找到学生,学号:{node.student_id}, 姓名:{node.name}, 电话:{node.phone}")
# 删除学生
students_list.delete_by_id(1001)
```
阅读全文