python用链表存储图书,并且打印链表的所有信息
时间: 2024-03-13 12:18:51 浏览: 110
python 数据结构与算法
可以使用Python中的类来表示图书,并使用链表来存储多个图书对象。下面是一个示例代码,可以通过该代码实现链表存储图书和打印链表信息的功能。
```python
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.next = None
class BookList:
def __init__(self):
self.head = None
def add_book(self, title, author, isbn):
new_book = Book(title, author, isbn)
if self.head is None:
self.head = new_book
else:
current_book = self.head
while current_book.next is not None:
current_book = current_book.next
current_book.next = new_book
def print_books(self):
current_book = self.head
while current_book is not None:
print("Title:", current_book.title)
print("Author:", current_book.author)
print("ISBN:", current_book.isbn)
current_book = current_book.next
```
使用上述代码,可以创建一个 `BookList` 对象来存储多个图书,并使用 `add_book` 方法向链表中添加新的图书对象。可以使用 `print_books` 方法打印链表中所有图书的信息。
例如,可以使用以下代码创建一个包含三本图书的链表,并打印所有图书的信息。
```python
book_list = BookList()
book_list.add_book("The Great Gatsby", "F. Scott Fitzgerald", "978-0141182636")
book_list.add_book("To Kill a Mockingbird", "Harper Lee", "978-0446310789")
book_list.add_book("1984", "George Orwell", "978-0451524935")
book_list.print_books()
```
输出结果如下:
```
Title: The Great Gatsby
Author: F. Scott Fitzgerald
ISBN: 978-0141182636
Title: To Kill a Mockingbird
Author: Harper Lee
ISBN: 978-0446310789
Title: 1984
Author: George Orwell
ISBN: 978-0451524935
```
阅读全文