以下是使用顺序表实现的代码:
#ifndef NULL
#define NULL 0
#endif
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int MAX_SIZE = 100; // 最大容量
struct LNode
{
// 存储数据
int month;
int day;
string name;
double price;
LNode() {}
LNode(int a, int b, string c, double d) : month(a), day(b), name(c), price(d) {}
};
class List
{
public:
LNode data[MAX_SIZE];
int _size;
public:
void init()
{
_size = 0;
}
List() { init(); } // 构造函数
~List() {} // 析构函数
void insert(int &a, int &b, string &c, double &d)
{
if (_size >= MAX_SIZE)
{
return;
}
for (int i = _size; i > 0; --i)
{
data[i] = data[i - 1];
}
data[0].month = a;
data[0].day = b;
data[0].name = c;
data[0].price = d;
++_size;
}
void insert(int index, int a, int b, string c, double d)
{
if (index <= 0 || index > _size + 1 || _size >= MAX_SIZE)
{
return;
}
for (int i = _size; i >= index; --i)
{
data[i] = data[i - 1];
}
data[index - 1].month = a;
data[index - 1].day = b;
data[index - 1].name = c;
data[index - 1].price = d;
++_size;
}
void print_L()
{
for (int i = 0; i < _size; ++i)
{
cout << data[i].month << " " << data[i].day << " ";
}
cout << endl;
}
int located(int a, int b)
{
for (int i = 0; i < _size; ++i)
{
if (a < data[i].month)
{
return i + 1;
}
else if (a == data[i].month)
{
if (b <= data[i].day)
{
return i + 1;
}
}
}
return _size + 1;
};
};
int main()
{
int m, n;
string str;
string c;
double d;
List L1;
double ave1 = 0.0;
double ave2 = 0.0;
cin >> m >> n;
for (int i = 0; i < m; ++i)
{
cin >> str >> c >> d;
int a = stoi(str.substr(2, str.size() - 2));
int b = stoi(str.substr(0, 2));
int e = L1.located(a, b);
L1.insert(e, a, b, c, d);
}
double sum1 = 0.0;
int count1 = 0;
double sum2 = 0.0;
int count2 = 0;
for (int i = 0; i < m && count1 < n; ++i)
{
if (L1.data[i].name == "keyboard")
{
sum1 += L1.data[i].price;
++count1;
}
}
for (int i = 0; i < m && count2 < n; ++i)
{
if (L1.data[i].name == "mouse")
{
sum2 += L1.data[i].price;
count2++;
}
}
cout << fixed << setprecision(1) << sum1 / n << endl;
cout << fixed << setprecision(1) << sum2 / n << endl;
return 0;
}
这段代码使用了顺序表实现,将链表改为数组,并进行相应的修改。
内容由零声教学AI助手提供,问题来源于学员提问




