用链表写1.借书2.还书3.查看已借图书
时间: 2024-12-16 20:18:14 浏览: 1
在链表上实现一个简单的图书管理系统,可以用单向链表来存储每本书的信息,包括标题、ID和借阅状态。以下是一个简化的实现:
首先,我们需要定义一个`Book`节点:
```c
typedef struct Node {
char* title;
int id;
enum {NOT_BORROWED, BORROWED} status;
struct Node* next;
} BookNode;
```
然后创建一个`Library`结构来维护链表:
```c
typedef struct Library {
BookNode* head;
int count;
} Library;
```
接下来,我们可以编写三个操作的函数:
1. **借书**:
```c
void borrow(Library* lib, int book_id) {
BookNode* book = find_book(lib->head, book_id); // 查找书
if (book && book->status == NOT_BORROWED) {
book->status = BORROWED;
lib->count++;
printf("成功借阅第%d本书 - %s\n", book_id, book->title);
} else {
printf("无法借阅该书。\n");
}
}
// 查找函数,用于找到指定ID的书节点
BookNode* find_book(BookNode* node, int id) {
while (node != NULL) {
if (node->id == id)
return node;
node = node->next;
}
return NULL;
}
```
2. **还书**:
```c
void return_book(Library* lib, int book_id) {
BookNode* book = find_book(lib->head, book_id);
if (book && book->status == BORROWED) {
book->status = NOT_BORROWED;
lib->count--;
printf("成功归还第%d本书 - %s\n", book_id, book->title);
} else {
printf("该书尚未借出。\n");
}
}
```
3. **查看已借图书**:
```c
void show_borrowed_books(Library* lib) {
BookNode* node = lib->head;
while (node != NULL) {
if (node->status == BORROWED) {
printf("已借出书籍:第%d本书 - %s\n", node->id, node->title);
}
node = node->next;
}
}
```
阅读全文