以下是使用单链表实现给定代码的示例:
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>
using namespace std;
struct Record {
int month;
int day;
string product;
double price;
Record* next; // 单链表指针
};
bool compare(Record a, Record b) {
if (a.month == b.month) {
return a.day > b.day;
} else {
return a.month > b.month;
}
}
int main() {
int m, n;
cin >> m >> n;
// 创建头结点
Record* head = new Record();
// 输入记录信息并构建单链表
for(int i = 0; i < m; i++) {
char slash;
// 创建新节点
Record* node = new Record();
cin >> node->month >> slash >> node->day >> node->product >> node->price;
// 将新节点插入到链表中
node->next = head->next;
head->next = node;
}
sort(records.begin(), records.end(), compare);
map<string, vector<double>> productPrices;
// 遍历单链表,按产品名称存储价格数据
Record* current = head->next;
while(current != NULL) {
if(productPrices[current->product].size() < n) {
productPrices[current->product].push_back(current->price);
}
current = current->next; // 指向下一个节点
}
delete head; // 释放头结点内存
for(auto& product : productPrices) {
double sum = 0;
for(auto& price : product.second) {
sum += price;
}
cout << fixed << setprecision(1) << sum / product.second.size() << endl;
}
return 0;
}
请注意,此处只是将给定的代码进行了修改以使用单链表存储数据。可能还需要对其进行进一步的测试和调试,以确保正确性和稳定性。
内容由零声教学AI助手提供,问题来源于学员提问