c语言基于图书ISBN、name、price信息,创建链表、插入、查找、删除、打印
时间: 2024-10-20 20:07:46 浏览: 29
在C语言中,我们可以使用结构体(struct)来表示图书的信息,包括ISBN、名称(name)和价格(price),然后通过链表数据结构来存储这些书籍。链表是一种动态的数据结构,节点之间通过指针连接。
首先,我们定义一个Book类型的结构体:
```c
typedef struct {
char isbn[10]; // 假设isbn最多10位数字
char name[50];
float price;
struct Book* next; // 指向下一个节点的指针
} Book;
```
接下来是链表的基本操作:
1. **创建链表**:
- 初始化一个空链表:`Book* head = NULL;`
2. **插入元素**:
```c
void insert(Book* &head, const char* isbn, const char* name, float price) {
Book* newNode = (Book*)malloc(sizeof(Book));
newNode->isbn = strdup(isbn);
newNode->name = strdup(name);
newNode->price = price;
newNode->next = head;
head = newNode;
}
```
3. **查找元素**:
```c
Book* search(Book* head, const char* isbn) {
while (head != NULL) {
if (strcmp(head->isbn, isbn) == 0)
return head;
head = head->next;
}
return NULL;
}
```
4. **删除元素**:
```c
void delete(Book** head, const char* isbn) {
Book* current = *head, *prev = NULL;
while (current != NULL && strcmp(current->isbn, isbn) != 0) {
prev = current;
current = current->next;
}
if (current == NULL)
return;
if (prev == NULL)
*head = current->next;
else
prev->next = current->next;
free(current); // 释放内存
}
```
5. **打印链表**:
```c
void printList(Book* head) {
if (head == NULL) {
printf("Empty list.\n");
return;
}
printf("Books:\n");
while (head != NULL) {
printf("%s, %s, %.2f\n", head->isbn, head->name, head->price);
head = head->next;
}
}
```
阅读全文