用C语言编写链表实现图书信息管理系统,每本书的编码、书名、定价作为线性表的一个元素。要求实现查找、插入、删除、修改、排序、计数六个功能
时间: 2024-10-14 20:09:11 浏览: 60
在C语言中,我们可以使用结构体来表示书籍信息,并创建一个链表来管理图书。下面是一个简单的链表实现,包含了查找、插入、删除、修改、排序以及计数这几个基本功能。
首先,我们定义一个书籍结构体:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int code; // 编码
char title[50]; // 书名
float price; // 定价
} Book;
// 链表节点结构
typedef struct Node {
Book info;
struct Node* next;
} Node;
```
接下来,我们可以实现链表的相关函数:
```c
// 创建新节点
Node* createBook(int code, const char* title, float price) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->info.code = code;
strncpy(newNode->info.title, title, sizeof(newNode->info.title));
newNode->info.price = price;
newNode->next = NULL;
return newNode;
}
// 添加书籍到链表
void insert(Book* book, Node** headRef) {
Node* newNode = createBook(book->code, book->title, book->price);
if (*headRef == NULL) {
*headRef = newNode;
} else {
Node* temp = *headRef;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// 查找书籍
Book* search(Node* head, int code) {
Node* temp = head;
while (temp != NULL) {
if (temp->info.code == code) {
return &temp->info;
}
temp = temp->next;
}
return NULL;
}
// 删除书籍
void deleteBook(Node** headRef, int code) {
if (*headRef == NULL) return;
if ((*headRef)->info.code == code) {
Node* temp = *headRef;
*headRef = (*headRef)->next;
free(temp);
return;
}
Node* prev = *headRef;
Node* curr = *headRef->next;
while (curr != NULL && curr->info.code != code) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
prev->next = curr->next;
free(curr);
}
// 修改书籍
void update(Book* book, Node* head) {
if (search(head, book->code)) {
node->info.title = book->title;
node->info.price = book->price;
}
}
// 对链表进行简单排序,例如按照价格升序排列
void sort(Node** head) {
if (*head == NULL || (*head)->next == NULL) return;
Node* small = *head;
Node* big = *head->next;
while (big != NULL) {
if (small->info.price > big->info.price) {
Book temp = small->info;
small->info = big->info;
big->info = temp;
}
small = small->next;
if (small != NULL) {
big = big->next;
}
}
}
// 计算链表中的书籍总数
int count(Node* head) {
int count = 0;
Node* temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
int main() {
Node* head = NULL;
// 使用以上函数添加、查找、删除、修改和排序书籍...
}
```
阅读全文