以下是使用单链表实现的代码:
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct LNode
{
int month;
int day;
string name;
double price;
LNode* next;
LNode(int a, int b, const string& c, double d) : month(a), day(b), name(c), price(d), next(nullptr) {}
};
class List
{
public:
int _size;
LNode* head;
List()
{
head = new LNode(0, 0, "", 0.0);
_size = 0;
}
~List()
{
while (head->next)
{
LNode* p = head->next;
head->next = p->next;
delete p;
}
delete head;
}
void insert(int a, int b, const string& c, double d)
{
LNode* p = head; // 头结点
while (p->next && (a > p->next->month || (a == p->next->month && b > p->next->day)))
p = p->next;
LNode* newNode = new LNode(a, b, c, d);
newNode->next = p->next; // 新节点的后继指向原来位置的元素
p->next = newNode; // 前一个节点的后继指向新节点
_size++;
}
void print_L()
{
LNode* p = head -> next;
while(p != nullptr)
{
cout << p -> month << " " << p -> day << " ";
p=p -> next ;
}
cout << endl ;
}
double getAveragePrice(const string& target, int n)
{
LNode* p = head->next;
double sum = 0.0;
int count = 0;
while(p != nullptr && count < n)
{
if(p->name == target)
{
sum += p->price;
count++;
}
p = p->next;
}
return sum / count;
}
};
int main()
{
int m, n;
string str, 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(2, 2));
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助手提供,问题来源于学员提问




