、编程实现建立一个学生单链表,并在此表中查找、插入和删除一个元素。
时间: 2024-09-23 18:14:21 浏览: 29
ListLink.rar_stl list_单链表_单链表 插入 删除 查找_链表 插入
在编程中,我们可以使用节点结构来创建一个简单的学生单链表。每个节点包含学生的数据(例如姓名、学号等)以及指向下一个节点的指针。以下是用Python语言实现一个基本的学生单链表结构及操作:
```python
class StudentNode:
def __init__(self, student_id, name):
self.student_id = student_id
self.name = name
self.next = None
class StudentList:
def __init__(self):
self.head = None
# 插入元素
def insert_student(self, student_id, name):
new_node = StudentNode(student_id, name)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 查找元素
def find_student(self, student_id):
if not self.head:
return None
current = self.head
while current and current.student_id != student_id:
current = current.next
return current if current else None
# 删除元素
def delete_student(self, student_id):
if not self.head:
return
if self.head.student_id == student_id:
self.head = self.head.next
return
prev = self.head
current = self.head.next
while current and current.student_id != student_id:
prev = current
current = current.next
if current:
prev.next = current.next
# 使用示例
student_list = StudentList()
student_list.insert_student(1001, "张三")
student = student_list.find_student(1001) # 返回找到的节点
student_list.delete_student(1001) # 删除指定学生
```
阅读全文