python用链表储存图书
时间: 2023-11-19 18:02:21 浏览: 78
用链表实现图书管理系统
4星 · 用户满意度95%
可以使用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 display_books(self):
current_book = self.head
while current_book is not None:
print(f"Title: {current_book.title}, Author: {current_book.author}, ISBN: {current_book.isbn}")
current_book = current_book.next
```
在上面的代码中,我们定义了一个`Book`类,它有三个属性:`title`、`author`和`isbn`,以及一个`next`属性,用于链接下一个节点。然后,我们定义了一个`BookList`类,它有一个`head`属性,用于保存链表的头节点。
`add_book`方法用于向链表中添加新书,如果链表为空,那么新书就成为头节点,否则我们遍历整个链表,找到最后一个节点,然后将新书添加到链表的末尾。
`display_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.display_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
```
这样,我们就可以使用链表来储存图书了。
阅读全文