基于线性表的图书信息管理系统C语言
时间: 2023-12-10 13:36:16 浏览: 168
基于线性表的图书信息管理系统C语言可以通过以下步骤实现:
1. 定义图书结构体和链表节点结构体
```c
typedef struct Book {
char BookNumber[50];
char BookName[50];
double price;
} Book;
typedef struct BookNode {
Book book;
struct BookNode* next;
} BookNode;
```
2. 定义链表的创建、插入、删除、遍历等操作函数
```c
// 创建链表
BookNode* CreateBookList();
// 获取链表长度
int GetBookListLength(BookNode* head);
// 遍历链表并打印每个节点的信息
void PrintBookList(BookNode* head);
// 向链表中插入一个节点
void InsertBookNode(BookNode* head, Book book, int index);
// 从链表中删除一个节点
void DeleteBookNode(BookNode* head, int index);
// 释放链表内存
void FreeBookList(BookNode* head);
```
3. 实现上述函数
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linklist.h"
// 创建链表
BookNode* CreateBookList() {
BookNode* head = (BookNode*)malloc(sizeof(BookNode));
head->next = NULL;
return head;
}
// 获取链表长度
int GetBookListLength(BookNode* head) {
int length = 0;
BookNode* p = head->next;
while (p != NULL) {
length++;
p = p->next;
}
return length;
}
// 遍历链表并打印每个节点的信息
void PrintBookList(BookNode* head) {
BookNode* p = head->next;
while (p != NULL) {
printf("BookNumber: %s, BookName: %s, price: %.2f\n", p->book.BookNumber, p->book.BookName, p->book.price);
p = p->next;
}
}
// 向链表中插入一个节点
void InsertBookNode(BookNode* head, Book book, int index) {
int length = GetBookListLength(head);
if (index < 0 || index > length) {
printf("Index out of range.\n");
return;
}
BookNode* p = head;
for (int i = 0; i < index; i++) {
p = p->next;
}
BookNode* new_node = (BookNode*)malloc(sizeof(BookNode));
new_node->book = book;
new_node->next = p->next;
p->next = new_node;
}
// 从链表中删除一个节点
void DeleteBookNode(BookNode* head, int index) {
int length = GetBookListLength(head);
if (index < 0 || index >= length) {
printf("Index out of range.\n");
return;
}
BookNode* p = head;
for (int i = 0; i < index; i++) {
p = p->next;
}
BookNode* q = p->next;
p->next = q->next;
free(q);
}
// 释放链表内存
void FreeBookList(BookNode* head) {
BookNode* p = head;
while (p != NULL) {
BookNode* q = p;
p = p->next;
free(q);
}
}
```
4. 在主函数中调用上述函数实现图书信息管理系统
```c
int main() {
BookNode* head = CreateBookList();
Book book1 = {"001", "C Programming", 59.9};
Book book2 = {"002", "Data Structure", 69.9};
Book book3 = {"003", "Algorithm", 79.9};
InsertBookNode(head, book1, 0);
InsertBookNode(head, book2, 1);
InsertBookNode(head, book3, 2);
PrintBookList(head);
DeleteBookNode(head, 1);
PrintBookList(head);
FreeBookList(head);
return 0;
}
```
阅读全文