我要用链表做图书管理系统功能有从文件中录入图书信息并输出图书信息查找图书信息借阅图书并记录归还图书退出程序
下面是一个使用链表实现图书管理系统的示例代码:
class Book:
def __init__(self, title, author, status="Available"):
self.title = title
self.author = author
self.status = status
self.next = None
class Library:
def __init__(self):
self.head = None
def add_book(self, book):
if self.head is None:
self.head = book
else:
current = self.head
while current.next:
current = current.next
current.next = book
def display_books(self):
if self.head is None:
print("No books available.")
else:
current = self.head
while current:
print("Title:", current.title)
print("Author:", current.author)
print("Status:", current.status)
print()
current = current.next
def find_book(self, title):
if self.head is None:
print("No books available.")
else:
current = self.head
while current:
if current.title.lower() == title.lower():
print("Book found:")
print("Title:", current.title)
print("Author:", current.author)
print("Status:", current.status)
print()
return
current = current.next
print("Book not found.")
def borrow_book(self, title):
if self.head is None:
print("No books available.")
else:
current = self.head
while current:
if current.title.lower() == title.lower():
if current.status == "Available":
current.status = "Borrowed"
print("Book borrowed successfully.")
else:
print("Book is already borrowed.")
return
current = current.next
print("Book not found.")
def return_book(self, title):
if self.head is None:
print("No books available.")
else:
current = self.head
while current:
if current.title.lower() == title.lower():
if current.status == "Borrowed":
current.status = "Available"
print("Book returned successfully.")
else:
print("Book is not borrowed.")
return
current = current.next
print("Book not found.")
# 主程序
library = Library()
while True:
print("1. Add book")
print("2. Display books")
print("3. Find book")
print("4. Borrow book")
print("5. Return book")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
title = input("Enter book title: ")
author = input("Enter book author: ")
book = Book(title, author)
library.add_book(book)
print("Book added successfully.")
elif choice == 2:
library.display_books()
elif choice == 3:
title = input("Enter book title: ")
library.find_book(title)
elif choice == 4:
title = input("Enter book title: ")
library.borrow_book(title)
elif choice == 5:
title = input("Enter book title: ")
library.return_book(title)
elif choice == 6:
print("Exiting program...")
break
else:
print("Invalid choice. Please try again.")
这个示例代码中,Book类表示图书,其中包含标题、作者和状态等属性。Library类表示图书馆,其中使用链表来存储图书对象。图书馆类提供了添加图书、显示图书、查找图书、借阅图书和归还图书的功能。主程序使用一个循环来接受用户的选择,并根据选择调用相应的图书馆方法
原文地址: https://www.cveoy.top/t/topic/hKAO 著作权归作者所有。请勿转载和采集!