基于线性表的图书管理程序
时间: 2023-12-10 15:32:36 浏览: 125
基于线性表的图书管理程序可以使用顺序表或链表来实现。以下是一个简单的基于链表的图书管理程序的示例:
1. 定义图书结构体
```
struct Book {
int id; // 图书编号
char title[50]; // 图书名称
char author[50]; // 作者
int year; // 出版年份
float price; // 价格
};
```
2. 定义链表节点结构体
```
struct Node {
Book book; // 图书信息
Node* next; // 指向下一个节点的指针
};
```
3. 实现添加图书功能
```
void addBook(Node*& head, Book book) {
Node* newNode = new Node;
newNode->book = book;
newNode->next = head;
head = newNode;
}
```
4. 实现删除图书功能
```
void deleteBook(Node*& head, int id) {
Node* prev = nullptr;
Node* curr = head;
while (curr != nullptr && curr->book.id != id) {
prev = curr;
curr = curr->next;
}
if (curr == nullptr) {
cout << "Book not found." << endl;
return;
}
if (prev == nullptr) {
head = curr->next;
} else {
prev->next = curr->next;
}
delete curr;
}
```
5. 实现查找图书功能
```
void findBook(Node* head, int id) {
Node* curr = head;
while (curr != nullptr && curr->book.id != id) {
curr = curr->next;
}
if (curr == nullptr) {
cout << "Book not found." << endl;
return;
}
cout << "Book found: " << curr->book.title << endl;
}
```
6. 实现显示所有图书功能
```
void displayBooks(Node* head) {
Node* curr = head;
while (curr != nullptr) {
cout << "ID: " << curr->book.id << endl;
cout << "Title: " << curr->book.title << endl;
cout << "Author: " << curr->book.author << endl;
cout << "Year: " << curr->book.year << endl;
cout << "Price: " << curr->book.price << endl;
cout << endl;
curr = curr->next;
}
}
```
阅读全文