在 Dev-C++ 上实现一个简单的链表来存储图书信息,并根据用户的输入进行查找,可以按照下面的代码进行: ```cpp #include <iostream> #include <iomanip> #include <string> using namespace std; struct Book { string id; // 书号 string title; // 书名 float price; // 价格 Book* next; // 指向下一个节点的指针 }; class BookList { public: BookList() : head(nullptr) {} void addBook(const string& id, const string& title, float price) { Book* newBook = new Book{id, title, price, nullptr}; if (head == nullptr) { head = newBook; } else { Book* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newBook; } } Book* getBookAt(int position) { Book* current = head; for (int i = 1; i < position && current != nullptr; ++i) { current = current->next; } return current; } ~BookList() { while (head != nullptr) { Book* temp = head; head = head->next; delete temp; } } private: Book* head; }; int main() { int n; cin >> n; BookList bookList; // 读入图书信息 for (int i = 0; i < n; ++i) { string id, title; float price; cin >> id >> title >> price; // 假设书名不含空格 bookList.addBook(id, title, price); } int m; cin >> m; // 进行查找 for (int i = 0; i < m; ++i) { int position; cin >> position; Book* book = bookList.getBookAt(position); if (book != nullptr) { cout << book->id << " " << book->title << " " << fixed << setprecision(2) << book->price << endl; } else { cout << "抱歉,指定位置上的图书不存在!" << endl; } } return 0; } ``` 代码说明: 1. 结构体定义:`Book` 结构体包含书号、书名、价格和指向下一个节点的指针。 2. 链表管理类:`BookList` 类负责管理链表,提供添加书籍和获取指定位置书籍的功能。 3. 添加书籍:通过 `addBook` 方法在链表尾部添加新的书籍。 4. 查找书籍:通过 `getBookAt` 方法根据位置查找书籍,返回相应的书籍指针。 5. 主函数: - 读入图书数量及每本书的信息并存入链表。 - 读入查询次数和查询位置,输出对应的图书信息或错误提示。 注意事项: - 为了简化输入,假设书名没有空格。如果需要处理书名中的空格,可以考虑使用 `getline` 并根据需要调整输入方式。 [2024-12-18 09:04:49 | AI写代码神器 | 1650点数解答]