c++基于链式存储结构的图书信息表的创建和输出
时间: 2023-12-19 12:06:23 浏览: 40
以下是一个基于链式存储结构的图书信息表的创建和输出的C++代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义图书信息结构体
struct Book {
string name; // 书名
string author; // 作者
int year; // 出版年份
Book* next; // 指向下一本书的指针
};
int main() {
// 创建第一本书
Book* head = new Book; // 创建头结点
head->name = "The Catcher in the Rye";
head->author = "J.D. Salinger";
head->year = 1951;
head->next = NULL;
// 创建第二本书
Book* book2 = new Book;
book2->name = "To Kill a Mockingbird";
book2->author = "Harper Lee";
book2->year = 1960;
book2->next = NULL;
// 将第二本书插入链表中
head->next = book2;
// 创建第三本书
Book* book3 = new Book;
book3->name = "1984";
book3->author = "George Orwell";
book3->year = 1949;
book3->next = NULL;
// 将第三本书插入链表中
book2->next = book3;
// 输出链表中的所有书籍信息
Book* current = head;
while (current != NULL) {
cout << "Book name: " << current->name << endl;
cout << "Author: " << current->author << endl;
cout << "Year: " << current->year << endl;
cout << endl;
current = current->next;
}
return 0;
}
```
在上述代码中,我们首先定义了一个名为 `Book` 的结构体,用于存储每一本书的信息。然后,在 `main` 函数中,我们创建了三本书,并将它们插入到一个链表中。最后,我们遍历链表,输出每一本书的信息。
需要注意的是,我们在创建头结点时,将 `next` 指针设置为 `NULL`,表示这是链表的头部。在创建其他节点时,我们将它们的 `next` 指针设置为 `NULL`,表示它们是链表中的最后一个节点。在将其他节点插入链表中时,我们需要更新前一个节点的 `next` 指针,使其指向新插入的节点。这样,我们就可以通过头结点来访问整个链表了。