数据结构图书借阅管理系统c++
时间: 2023-07-06 15:25:46 浏览: 40
好的,你需要一个数据结构来存储图书信息和借阅记录。以下是一个简单的C++程序示例,展示了如何使用链表来实现这个系统:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义图书结构体
struct Book {
string name;
string author;
int id;
bool borrowed;
Book* next;
};
// 定义图书馆类
class Library {
private:
Book* head;
public:
// 构造函数
Library() {
head = NULL;
}
// 添加图书
void addBook(string name, string author, int id) {
Book* newBook = new Book;
newBook->name = name;
newBook->author = author;
newBook->id = id;
newBook->borrowed = false;
newBook->next = head;
head = newBook;
}
// 借书
void borrowBook(int id) {
Book* current = head;
while (current != NULL) {
if (current->id == id) {
if (current->borrowed) {
cout << "This book has already been borrowed." << endl;
} else {
current->borrowed = true;
cout << "Book successfully borrowed." << endl;
}
return;
}
current = current->next;
}
cout << "Book not found." << endl;
}
// 还书
void returnBook(int id) {
Book* current = head;
while (current != NULL) {
if (current->id == id) {
if (current->borrowed) {
current->borrowed = false;
cout << "Book successfully returned." << endl;
} else {
cout << "This book has not been borrowed." << endl;
}
return;
}
current = current->next;
}
cout << "Book not found." << endl;
}
// 显示图书列表
void displayBooks() {
Book* current = head;
while (current != NULL) {
cout << "Book Name: " << current->name << endl;
cout << "Author: " << current->author << endl;
cout << "ID: " << current->id << endl;
if (current->borrowed) {
cout << "Status: Borrowed" << endl;
} else {
cout << "Status: Available" << endl;
}
cout << endl;
current = current->next;
}
}
};
// 主函数
int main() {
Library library;
library.addBook("Data Structures and Algorithms", "Adam Drozdek", 1001);
library.addBook("Introduction to Algorithms", "Thomas H. Cormen", 1002);
library.addBook("Programming Pearls", "Jon Bentley", 1003);
while (true) {
int choice;
cout << "1. Display Books" << endl;
cout << "2. Borrow Book" << endl;
cout << "3. Return Book" << endl;
cout << "4. Quit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == 1) {
library.displayBooks();
} else if (choice == 2) {
int id;
cout << "Enter book ID: ";
cin >> id;
library.borrowBook(id);
} else if (choice == 3) {
int id;
cout << "Enter book ID: ";
cin >> id;
library.returnBook(id);
} else {
break;
}
}
return 0;
}
```
在这个系统中,我们使用了一个链表来存储图书信息。每个图书都是一个包含书名、作者、ID和借阅状态的结构体。我们可以使用 `addBook()` 方法向图书馆中添加书籍,使用 `borrowBook()` 方法借阅书籍,使用 `returnBook()` 方法归还书籍,使用 `displayBooks()` 方法显示当前图书馆中的书籍列表。
当用户选择退出时,程序将结束。