下面是一段在 Dev-C++ 中实现包含书籍信息的链表的完整代码。该代码用于读入图书数据并根据指定的最佳位置查找相应的图书,最终输出图书的相关信息。 ```cpp #include <iostream> #include <iomanip> #include <cstring> using namespace std; // 定义图书信息结构体 struct Book { char id[30]; // 书号 char title[100]; // 书名 float price; // 价格 Book *next; // 指向下一个节点的指针 }; // 创建链表的头指针 Book *head = nullptr; // 添加图书到链表 void addBook(const char *id, const char *title, float price) { Book *newBook = new Book; strcpy(newBook->id, id); strcpy(newBook->title, title); newBook->price = price; newBook->next = nullptr; if (head == nullptr) { head = newBook; } else { Book *current = head; while (current->next != nullptr) { current = current->next; } current->next = newBook; } } // 查找指定位置的图书 Book* findBookByPosition(int position) { Book *current = head; int index = 1; // 从1开始计数 while (current != nullptr && index < position) { current = current->next; index++; } return current; } int main() { int n, m; // 输入图书数量 cin >> n; cin.ignore(); // 处理掉换行符 // 输入图书信息 for (int i = 0; i < n; i++) { char id[30], title[100]; float price; cin >> id >> title >> price; // 读入书号、书名和价格 addBook(id, title, price); cin.ignore(); // 处理掉换行符 } // 输入查找次数 cin >> m; // 查找每次指定位置的图书 for (int i = 0; i < m; i++) { int position; cin >> position; Book *foundBook = findBookByPosition(position); if (foundBook != nullptr) { // 查找成功 cout << foundBook->id << " " << foundBook->title << " " << fixed << setprecision(2) << foundBook->price << endl; } else { // 查找失败 cout << "抱歉,指定位置上的图书不存在!" << endl; } } // 清理链表内存 while (head != nullptr) { Book *temp = head; head = head->next; delete temp; } return 0; } ``` 说明 1. 结构体定义: `Book` 是一个结构体,用于存储书号、书名、价格和指向下一个书籍节点的指针。 2. 添加图书: `addBook` 函数将新的图书信息添加到链表的末尾。 3. 查找图书: `findBookByPosition` 函数根据给定的位置查找图书。 4. 主函数: - 首先读取总图书数量并输入每本图书的信息。 - 然后读取要查找的位置,并输出相应图书的信息,格式化价格为两位小数。 5. 内存管理: 在程序结束前清理链表以释放内存。 使用示例 输入和输出示例在代码中已注释,用户可以根据需求输入数据进行测试。 [2024-12-18 09:04:51 | AI写代码神器 | 1823点数解答]