以下是使用另一种方法实现给定代码的修改版本:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct LNode
{
int month;
int day;
string name;
double price;
LNode* next;
LNode() : next(nullptr) {}
LNode(int a, int b, const string& c, double d) : month(a), day(b), name(c), price(d), next(nullptr) {}
};
class List
{
public:
LNode* head;
List()
{
head = new LNode();
head->next = nullptr;
}
~List()
{
while (head)
{
LNode* temp = head->next;
delete head;
head = temp;
}
}
// 头插法插入节点
void insert(int a, int b, const string& c, double d)
{
LNode* newNode = new LNode(a, b, c, d);
newNode->next = head->next;
head->next = newNode;
}
void print_L()
{
LNode* p = head->next;
while (p)
{
cout << p->month << " " << p->day << " ";
p = p->next;
}
cout << endl;
}
int located(int a, int b)
{
int e = 1; // 初始位置从1开始
LNode* p = head->next;
while (p)
{
if (a < p->month || (a == p->month && b <= p->day))
return e;
e++;
p = p->next;
}
return e;
}
};
int main()
{
int m, n;
string str;
string c;
double d;
cin >> m >> n;
List L1;
for (int i = 0; i < m; i++)
{
cin >> str >> c >> d;
int a = stoi(str.substr(0, 2));
int b = stoi(str.substr(3));
int e = L1.located(a, b);
L1.insert(a, b, c, d);
}
double sum1 = 0.0;
int count1 = 0;
double sum2 = 0.0;
int count2 = 0;
LNode* p = L1.head->next;
while (p && count1 < n)
{
if (p->name == "keyboard")
{
sum1 += p->price;
count1++;
}
p = p->next;
}
LNode* s = L1.head->next;
while (s && count2 < n)
{
if (s->name == "mouse")
{
sum2 += s->price;
count2++;
}
s = s->next;
}
cout << fixed << setprecision(1) << sum1 / n << endl;
cout << fixed << setprecision(1) << sum2 / n << endl;
return 0;
}
这个修改版本将代码进行了重构和调整,但保持了相同的逻辑和功能。
内容由零声教学AI助手提供,问题来源于学员提问