下面是使用顺序表修改后的代码:
#ifndef NULL
#define NULL 0
#endif
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
struct LNode
{
//存储数据
int month;
int day;
string name;
double price;
};
class List
{
public:
int _size;
LNode* data; // 顺序表存储数据
static const int MAX_SIZE = 100; // 最大容量
void init() {
data = new LNode[MAX_SIZE];
_size = 0;
}
List() { init(); }//构造函数
~List()
{
delete[] data;
}
void insert(int& a, int& b, string& c, double& d)
{
if (_size >= MAX_SIZE)
return;
for (int i = _size - 1; i >= 0; i--)
data[i + 1] = data[i];
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 - 1; i >= index - 1; i--)
data[i + 1] = data[i];
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)
{
int e = 1;
for (int i = 0; i < _size; i++)
{
if (a < data[i].month)
return e;
if (a == data[i].month && b <= data[i].day)
return e;
e++;
}
return e;
}
};
int main()
{
int m, n;
string str;
string c;
double d;
List L1;
double ave1 = 0;
double ave2 = 0;
cin >> m >> n;
for (int i = 0; i < m; i++)
{
cin >> str >> c >> d;
int a = stoi(str, 0, 10);
if (a >= 10)
str.erase(0, 3);
else
str.erase(0, 2);
int b = stoi(str, 0, 10);
int e = L1.located(a, b);
L1.insert(e, a, b, c, d);
}
//L1.print_L();
double sum1 = 0;
int count1 = 0;
double sum2 = 0;
int count2 = 0;
for (int i = 0; i < L1._size && count1 < n; i++)
{
if (L1.data[i].name == "keyboard")
{
sum1 += L1.data[i].price;
count1++;
}
}
for (int i = 0; i < L1._size && 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助手提供,问题来源于学员提问




