以下是使用单链表实现给定代码的示例:
#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 = nullptr; // 链表头指针
for(int i = 0; i < m; i++) {
char slash;
// 创建新节点
Record* newNode = new Record();
cin >> newNode->month >> slash >> newNode->day >> newNode->product >> newNode->price;
newNode->next = head; // 将新节点插入链表头部
head = newNode; // 更新链表头指针
}
sort(records.begin(), records.end(), compare);
map<string, vector<double>> productPrices;
// 遍历链表进行处理
Record* current = head;
while(current != nullptr){
if(productPrices[current->product].size() < n) {
productPrices[current->product].push_back(current->price);
}
current = current->next; // 移动到下一个节点
}
delete current; // 删除最后一个节点
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助手提供,问题来源于学员提问




