可以使用链表实现该代码,下面是另一种方法的实现:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct LNode {
int month;
int day;
string name;
double price;
LNode* next;
LNode(int m, int d, string n, double p) : month(m), day(d), name(n), price(p), next(nullptr) {}
};
class List {
public:
int size;
LNode* head;
List() : size(0), head(nullptr) {}
~List() {
LNode* current = head;
while (current != nullptr) {
LNode* next = current->next;
delete current;
current = next;
}
head = nullptr;
}
void insert(int m, int d, const string& n, double p) {
size++;
LNode* newNode = new LNode(m, d, n, p);
if (head == nullptr || (m < head->month) || (m == head->month && d < head->day)) {
newNode->next = head;
head = newNode;
} else {
LNode* current = head;
while (current->next != nullptr &&
((current->next)->month < m || ((current->next)->month == m && (current->next)->day <= d))) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void print_L() const {
LNode* current = head;
while (current != nullptr) {
cout << setw(2) << setfill('0') << current->month << " ";
cout << setw(2) << setfill('0') << current->day << " ";
cout << current->name << " ";
cout << fixed << setprecision(1) << current->price;
cout << endl;
current = current->next;
}
}
double averagePrice(const string& item, int n) const {
LNode* current = head;
double sum = 0.0;
int count = 0;
while (current != nullptr && count < n) {
if (current->name == item) {
sum += current->price;
count++;
}
current = current->next;
}
return sum / count;
}
};
int main() {
int m, n;
cin >> m >> n;
List L1;
for (int i = 0; i < m; i++) {
string str, name;
double price;
cin >> str >> name >> price;
int month = stoi(str.substr(2, 2));
int day = stoi(str.substr(4, 2));
L1.insert(month, day, name, price);
}
//L1.print_L();
double avgKeyboardPrice = L1.averagePrice("keyboard", n);
double avgMousePrice = L1.averagePrice("mouse", n);
cout << fixed << setprecision(1) << avgKeyboardPrice << endl
<< fixed << setprecision(1) << avgMousePrice<< endl;
return 0;
}
这个实现使用了链表来存储数据,按照月份和日期的顺序插入节点。然后,根据要求计算键盘和鼠标商品的平均价格,并输出结果。
内容由零声教学AI助手提供,问题来源于学员提问




