用单链表写一个图书信息管理系统
时间: 2023-05-28 14:08:17 浏览: 139
这是一个基于单链表的图书信息管理系统,支持添加图书、删除图书、查找图书和显示所有图书信息等基本操作:
```python
class Book:
def __init__(self, name, author, price, pub_date):
self.name = name
self.author = author
self.price = price
self.pub_date = pub_date
self.next = None
class BookList:
def __init__(self):
self.head = None
def add_book(self, name, author, price, pub_date):
book = Book(name, author, price, pub_date)
if self.head is None:
self.head = book
else:
node = self.head
while node.next is not None:
node = node.next
node.next = book
def remove_book(self, name):
if self.head is None:
return
if self.head.name == name:
self.head = self.head.next
return
node = self.head
while node.next is not None:
if node.next.name == name:
node.next = node.next.next
return
node = node.next
def find_book(self, name):
node = self.head
while node is not None:
if node.name == name:
return node
node = node.next
return None
def display_books(self):
node = self.head
while node is not None:
print(f"{node.name}\t{node.author}\t{node.price}\t{node.pub_date}")
node = node.next
```
下面是一个简单的使用示例:
```python
book_list = BookList()
book_list.add_book("Python深度学习", "Francois Chollet", 99.0, "2018-10-08")
book_list.add_book("机器学习实战", "Peter Harrington", 69.0, "2012-06-08")
book_list.add_book("深入浅出机器学习", "李航", 59.0, "2012-04-01")
book_list.display_books()
book_list.remove_book("Python深度学习")
book_list.display_books()
book = book_list.find_book("机器学习实战")
if book is not None:
print(f"找到了书籍:{book.name}\t{book.author}\t{book.price}\t{book.pub_date}")
else:
print("没有找到该书籍")
```
输出结果:
```
Python深度学习 Francois Chollet 99.0 2018-10-08
机器学习实战 Peter Harrington 69.0 2012-06-08
深入浅出机器学习 李航 59.0 2012-04-01
机器学习实战 Peter Harrington 69.0 2012-06-08
找到了书籍:机器学习实战 Peter Harrington 69.0 2012-06-08
```
阅读全文