用Python写一个基于链式存储的图书信息管理系统,(1)首先将该文件中的图书信息读入到一个链表中 (2)至少实现以下6个功能:查找、插入、删除、修改、排序、显示所有图书信息等,
时间: 2024-12-14 09:19:51 浏览: 16
在Python中,我们可以使用类(class)和链式数据结构(如节点ListNode)来构建一个简单的图书信息管理系统。下面是一个基本的设计:
```python
# 定义图书节点类
class BookNode:
def __init__(self, title, author, id):
self.title = title
self.author = author
self.id = id
self.next = None
# 图书管理链表类
class BookList:
def __init__(self):
self.head = None
# 插入函数
def insert(self, title, author, id):
new_node = BookNode(title, author, id)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 查找函数
def search(self, id):
current = self.head
while current and current.id != id:
current = current.next
return current is not None
# 删除函数
def delete(self, id):
if not self.head:
return
if self.head.id == id:
self.head = self.head.next
return
prev = None
current = self.head
while current and current.id != id:
prev = current
current = current.next
if current is not None:
prev.next = current.next
# 修改函数
def update(self, old_id, new_title, new_author):
current = self.head
while current:
if current.id == old_id:
current.title = new_title
current.author = new_author
break
current = current.next
# 显示所有图书信息
def display(self):
items = []
current = self.head
while current:
items.append((current.id, current.title, current.author))
current = current.next
for id, title, author in items:
print(f"ID: {id}, Title: {title}, Author: {author}")
# 示例用法
book_list = BookList()
# ... (从文件或其他源读取图书信息并插入链表)
# 调用各种操作
book_list.insert("书名", "作者", 1) # 插入图书
if book_list.search(1): # 查找特定图书
print("找到了")
else:
print("未找到")
book_list.delete(1) # 删除图书
book_list.update(1, "新书名", "新作者") # 修改图书
book_list.display() # 显示所有图书信息
```
这个例子是一个基础版本,实际应用中可能会需要处理更复杂的情况,例如错误处理、文件输入/输出以及链表遍历优化。
阅读全文