下面是使用C++11标准的另一种实现方式:
#include
using namespace std;
struct LNode {
int month;
int day;
string name;
double price;
shared_ptr<LNode> next; // 使用智能指针
};
class List { private:
shared_ptr<LNode> head;
int size;
public:
List() : head(nullptr), size(0) {}
void insert(int a, int b, const string& c, double d)
{
shared_ptr<LNode> newNode = make_shared<LNode>();
newNode->month = a;
newNode->day = b;
newNode->name = c;
newNode->price = d;
newNode->next = nullptr;
if (head == nullptr)
{
head = newNode;
}
else
{
shared_ptr<LNode> p = head;
while (p->next != nullptr)
{
p = p->next;
}
p->next = newNode;
}
size++;
}
double getAveragePrice(const string& itemName, int count)
{
double sum = 0.0;
shared_ptr<LNode> p = head;
for (int i = 0; i < size && count > 0; i++)
{
if (p && p->name == itemName)
{
sum += p->price;
count--;
}
p = p->next;
}
return sum / count;
}
};
int main() {
int m, n;
cin >> m >> n;
List L1;
for (int i = 0; i < m; i++)
{
string str;
cin >> str;
int a = stoi(str.substr(0, 2));
int b = stoi(str.substr(3, 2));
string c;
double d;
cin >> c >> d;
L1.insert(a, b, c, d);
}
double ave1 = L1.getAveragePrice("keyboard", n);
double ave2 = L1.getAveragePrice("mouse", n);
cout << fixed << setprecision(1) << ave1 << endl;
cout << fixed << setprecision(1) << ave2 << endl;
return 0;
}
内容由零声教学AI助手提供,问题来源于学员提问