用c语言的链表实现图书管理系统
时间: 2024-12-12 10:32:48 浏览: 13
在C语言中,我们可以利用链表数据结构来实现一个简单的图书管理系统。链表非常适合这种需要频繁插入、删除元素的情况,因为它们可以在常数时间内添加或删除节点。这里是一个基本的概念框架:
1. **节点定义**:
```c
typedef struct Node {
char bookName[100]; // 图书名称
int authorID; // 作者ID
struct Node* next; // 指向下一个节点的指针
} BookNode;
```
2. **链表头节点**:
```c
BookNode* libraryHead = NULL;
```
3. **添加书籍**:
```c
void addBook(char* name, int author) {
BookNode* newNode = (BookNode*)malloc(sizeof(BookNode));
strcpy(newNode->bookName, name);
newNode->authorID = author;
newNode->next = libraryHead;
libraryHead = newNode;
}
```
4. **查找书籍**:
```c
BookNode* findBookByAuthor(int authorID) {
BookNode* currentNode = libraryHead;
while (currentNode != NULL) {
if (currentNode->authorID == authorID) {
return currentNode;
}
currentNode = currentNode->next;
}
return NULL; // 如果未找到,则返回NULL
}
```
5. **删除书籍**:
```c
void deleteBookByAuthor(int authorID) {
if (libraryHead == NULL) return;
if (libraryHead->authorID == authorID) {
BookNode* temp = libraryHead;
libraryHead = libraryHead->next;
free(temp);
return;
}
BookNode* prev = libraryHead;
BookNode* currentNode = libraryHead->next;
while (currentNode != NULL && currentNode->authorID != authorID) {
prev = currentNode;
currentNode = currentNode->next;
}
if (currentNode != NULL) {
prev->next = currentNode->next;
free(currentNode);
}
}
```
6. **显示所有书籍**:
```c
void displayBooks() {
BookNode* currentNode = libraryHead;
while (currentNode != NULL) {
printf("书名:%s, 作者ID:%d\n", currentNode->bookName, currentNode->authorID);
currentNode = currentNode->next;
}
}
```
以上就是一个基本的图书管理系统链表实现,实际项目中还需要考虑更多的细节,例如错误检查和用户交互界面。
阅读全文