用C语言实现线性结构-基于线性表的图书信息系统
时间: 2024-10-19 09:08:52 浏览: 25
在C语言中实现基于线性表的图书信息系统,通常会涉及到链表数据结构。下面是一个简单的例子,我们将创建一个图书节点和一个包含书籍信息的链表结构,以及一些基本操作,如添加、删除和查找图书。
首先,定义一个图书节点结构体(BookNode):
```c
typedef struct {
char title[100]; // 图书标题
int author; // 作者ID
int id; // 图书唯一标识
struct BookNode* next; // 指向下一个节点的指针
} BookNode;
```
接下来,我们创建链表相关的函数:
1. 初始化链表:
```c
BookNode* initList() {
BookNode* head = NULL;
return head;
}
```
2. 添加图书:
```c
void addBook(BookNode** head, char title[], int author, int id) {
BookNode* newNode = (BookNode*)malloc(sizeof(BookNode));
if (newNode) {
strcpy(newNode->title, title);
newNode->author = author;
newNode->id = id;
newNode->next = *head;
*head = newNode;
} else {
printf("Memory allocation failed.\n");
}
}
```
3. 删除图书:
```c
void deleteBook(BookNode** head, int id) {
BookNode* current = *head, *prev = NULL;
while (current != NULL && current->id != id) {
prev = current;
current = current->next;
}
if (current != NULL) {
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;
}
free(current);
} else {
printf("Book not found.\n");
}
}
```
4. 查找图书:
```c
BookNode* searchBook(BookNode* head, int id) {
BookNode* current = head;
while (current != NULL) {
if (current->id == id) {
return current;
}
current = current->next;
}
return NULL;
}
```
阅读全文