用c语言编写链式结构图书信息表,包含输入书籍的id,名字,价格,通过id查找书籍,删除书籍功能
时间: 2024-10-21 10:14:52 浏览: 33
在C语言中,我们可以使用链表数据结构来创建一个简单的图书信息表。首先,我们需要定义一个链表节点结构,存储书籍的基本信息,包括ID、名称和价格。然后创建一个链表头指针,并提供添加、查找和删除书籍的功能。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct BookNode {
int id;
char name[50];
float price;
struct BookNode* next;
} BookNode;
// 创建新节点并初始化
BookNode* createNewBook(int id, const char* name, float price) {
BookNode* newNode = (BookNode*)malloc(sizeof(BookNode));
if (newNode != NULL) {
newNode->id = id;
strncpy(newNode->name, name, sizeof(newNode->name) - 1);
newNode->price = price;
newNode->next = NULL;
}
return newNode;
}
// 添加书籍到链表
void addBook(BookNode** head, int id, const char* name, float price) {
BookNode* newNode = createNewBook(id, name, price);
if (*head == NULL) {
*head = newNode;
} else {
BookNode* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 查找书籍
BookNode* findBook(BookNode* head, int id) {
BookNode* current = head;
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL; // 如果找不到,返回NULL
}
// 删除书籍
void deleteBook(BookNode** head, int id) {
if (*head == NULL) return; // 空链表无需操作
if ((*head)->id == id) { // 如果头节点就是目标
BookNode* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
BookNode* prev = *head;
BookNode* current = *head->next;
while (current != NULL && current->id != id) {
prev = current;
current = current->next;
}
if (current == NULL) return; // 没找到目标
prev->next = current->next;
free(current); // 释放内存
}
// 打印链表内容
void displayBooks(BookNode* head) {
BookNode* current = head;
while (current != NULL) {
printf("ID: %d, Name: %s, Price: %.2f\n", current->id, current->name, current->price);
current = current->next;
}
}
int main() {
BookNode* bookList = NULL;
// 添加一些书籍示例
addBook(&bookList, 1, "书名1", 19.99);
addBook(&bookList, 2, "书名2", 24.99);
// 查找书籍
BookNode* foundBook = findBook(bookList, 1);
if (foundBook) {
printf("Found book with ID: %d\n", foundBook->id);
} else {
printf("Book not found.\n");
}
// 删除书籍
deleteBook(&bookList, 1);
displayBooks(bookList);
return 0;
}
```
阅读全文