python用链表写图书管理系统
时间: 2023-07-18 18:29:50 浏览: 121
好的,那我来为您讲解如何使用 Python 链表实现一个简单的图书管理系统。
首先,我们需要定义一个图书类,表示每一本图书,包括书名、作者、出版社、出版日期等属性。代码如下:
```python
class Book:
def __init__(self, title, author, publisher, publish_date):
self.title = title
self.author = author
self.publisher = publisher
self.publish_date = publish_date
```
接着,我们需要定义一个链表类,用于存储图书信息。链表中的每一个节点表示一本图书。代码如下:
```python
class Node:
def __init__(self, book):
self.book = book
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_book(self, book):
node = Node(book)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def remove_book(self, title):
if not self.head:
return
if self.head.book.title == title:
self.head = self.head.next
else:
prev = self.head
cur = self.head.next
while cur:
if cur.book.title == title:
prev.next = cur.next
if not cur.next:
self.tail = prev
break
prev = cur
cur = cur.next
def search_book(self, title):
cur = self.head
while cur:
if cur.book.title == title:
return cur.book
cur = cur.next
return None
def show_books(self):
cur = self.head
while cur:
print(cur.book.title, cur.book.author, cur.book.publisher, cur.book.publish_date)
cur = cur.next
```
在上述代码中,add_book() 方法用于添加新的图书,remove_book() 方法用于删除指定书名的图书,search_book() 方法用于查找指定书名的图书,show_books() 方法用于显示所有图书的信息。
最后,我们可以创建一个 LinkedList 对象,并调用其方法来进行测试。例如:
```python
book_list = LinkedList()
book_list.add_book(Book("Python基础教程", "Magnus Lie Hetland", "人民邮电出版社", "2017-01-01"))
book_list.add_book(Book("Python数据分析与挖掘实战", "菜菜", "人民邮电出版社", "2018-01-01"))
book_list.add_book(Book("Python编程从入门到实践", "Eric Matthes", "人民邮电出版社", "2017-04-01"))
book_list.show_books()
book_list.remove_book("Python数据分析与挖掘实战")
book_list.show_books()
book = book_list.search_book("Python编程从入门到实践")
if book:
print(book.title, book.author, book.publisher, book.publish_date)
else:
print("未找到该图书")
```
运行上述代码,即可看到图书信息的增删查等操作结果。
阅读全文