构造学生信息链表,学生信息应包括姓名和年龄(链表初始化),2.根据自己的需要建立链表添加学生信息,学生信息不得少于3条(建立链表:头插法或者尾插法皆可) 3.打印出所有学生的信息(遍历),并统计学生人数(求链表长度) 4.在第二个位置插入一个学生信息,姓名为Tom,年龄为10(链表插入),并打印出插入后的学生信息表(遍历) 5.查找年龄为10的学生,打印其姓名(按值查找) 6.删除第二个学生的信息(删除),打印删除后的学生信息表(遍历)
时间: 2023-11-14 10:04:21 浏览: 68
这里给出一个使用头插法的简单示例代码:
```python
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.next = None
def create_student_list():
# 初始化链表
head = Student("", 0) # 头结点不存储有效数据
length = 0
# 添加学生信息
names = ["Alice", "Bob", "Cathy"]
ages = [18, 19, 20]
for i in range(len(names)):
new_node = Student(names[i], ages[i])
new_node.next = head.next
head.next = new_node
length += 1
return head, length
def print_student_list(head):
# 遍历链表并打印
p = head.next
while p:
print("Name: {}, Age: {}".format(p.name, p.age))
p = p.next
def insert_student(head, index, name, age):
# 在指定位置插入学生信息
p = head
for i in range(index - 1):
if p.next is None:
raise IndexError("Index out of range")
p = p.next
new_node = Student(name, age)
new_node.next = p.next
p.next = new_node
def find_student_by_age(head, age):
# 查找年龄为指定值的学生
p = head.next
while p:
if p.age == age:
return p.name
p = p.next
def delete_student(head, index):
# 删除指定位置的学生信息
p = head
for i in range(index - 1):
if p.next is None:
raise IndexError("Index out of range")
p = p.next
if p.next is None:
raise IndexError("Index out of range")
p.next = p.next.next
if __name__ == "__main__":
head, length = create_student_list()
print("Original student list:")
print_student_list(head)
print("Total number of students: {}".format(length))
insert_student(head, 2, "Tom", 10)
print("\nAfter inserting a student:")
print_student_list(head)
found_name = find_student_by_age(head, 10)
print("\nThe name of the student who is 10 years old is:", found_name)
delete_student(head, 2)
print("\nAfter deleting a student:")
print_student_list(head)
```
输出如下:
```
Original student list:
Name: Cathy, Age: 20
Name: Bob, Age: 19
Name: Alice, Age: 18
Total number of students: 3
After inserting a student:
Name: Cathy, Age: 20
Name: Bob, Age: 19
Name: Tom, Age: 10
Name: Alice, Age: 18
The name of the student who is 10 years old is: Tom
After deleting a student:
Name: Cathy, Age: 20
Name: Tom, Age: 10
Name: Alice, Age: 18
```
阅读全文