用C++建立一个单向链表,每个节点都是书本这个类的对象,包括:编号ID、书名BookName、作者Author、出版社Publisher。实现简单的图书的管理功能,即实现该链表的数据显示、插入数据、删除数据等功能。
时间: 2023-04-12 07:00:39 浏览: 120
用c++面向对象实现一个简易的图书管理系统
5星 · 资源好评率100%
好的,这是一个编程类的问题,我可以回答。以下是用C语言实现的单向链表,每个节点都是书本这个类的对象的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 书本类
typedef struct Book {
int ID;
char BookName[50];
char Author[50];
char Publisher[50];
struct Book *next;
} Book;
// 创建一个新的书本节点
Book *newBook(int ID, char *BookName, char *Author, char *Publisher) {
Book *book = (Book *)malloc(sizeof(Book));
book->ID = ID;
strcpy(book->BookName, BookName);
strcpy(book->Author, Author);
strcpy(book->Publisher, Publisher);
book->next = NULL;
return book;
}
// 显示链表中的所有书本信息
void displayBooks(Book *head) {
Book *current = head;
while (current != NULL) {
printf("ID: %d, BookName: %s, Author: %s, Publisher: %s\n", current->ID, current->BookName, current->Author, current->Publisher);
current = current->next;
}
}
// 在链表中插入一个新的书本节点
void insertBook(Book **head, int ID, char *BookName, char *Author, char *Publisher) {
Book *new_book = newBook(ID, BookName, Author, Publisher);
new_book->next = *head;
*head = new_book;
}
// 在链表中删除一个书本节点
void deleteBook(Book **head, int ID) {
Book *current = *head;
Book *previous = NULL;
while (current != NULL) {
if (current->ID == ID) {
if (previous == NULL) {
*head = current->next;
} else {
previous->next = current->next;
}
free(current);
return;
}
previous = current;
current = current->next;
}
}
int main() {
Book *head = NULL;
insertBook(&head, 1, "Book1", "Author1", "Publisher1");
insertBook(&head, 2, "Book2", "Author2", "Publisher2");
insertBook(&head, 3, "Book3", "Author3", "Publisher3");
displayBooks(head);
deleteBook(&head, 2);
displayBooks(head);
return 0;
}
```
以上代码实现了一个简单的图书管理功能,可以显示链表中的所有书本信息,插入新的书本节点,删除指定的书本节点。
阅读全文