学生宿舍管理系统单链表实现pythno
时间: 2024-02-15 21:04:12 浏览: 89
以下是一个简单的学生宿舍管理系统单链表实现的 Python 代码:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Student:
def __init__(self, name, id, room):
self.name = name
self.id = id
self.room = room
class Dormitory:
def __init__(self):
self.head = Node()
def add_student(self, student):
new_node = Node(student)
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def remove_student(self, id):
current_node = self.head
while current_node.next is not None:
if current_node.next.data.id == id:
current_node.next = current_node.next.next
return
current_node = current_node.next
print("Student with ID {} not found".format(id))
def display_students(self):
current_node = self.head.next
while current_node is not None:
print("Name: {}, ID: {}, Room: {}".format(current_node.data.name, current_node.data.id, current_node.data.room))
current_node = current_node.next
```
使用示例:
```python
dorm = Dormitory()
student1 = Student("Tom", 123, "A101")
student2 = Student("John", 456, "A102")
dorm.add_student(student1)
dorm.add_student(student2)
dorm.display_students() # Output: Name: Tom, ID: 123, Room: A101 Name: John, ID: 456, Room: A102
dorm.remove_student(123)
dorm.display_students() # Output: Name: John, ID: 456, Room: A102
```
在上面的示例中,我们首先创建了一个 `Dormitory` 对象,然后创建了两个 `Student` 对象并添加到宿舍管理系统中。接着我们打印出了所有的学生信息,然后删除了 ID 为 123 的学生,再次打印出了所有的学生信息。
阅读全文