将代码修改为使用顺序表实现后的版本如下所示:
#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; // 数据存储数组
List()
{
_size = 0;
data = new LNode[100]; // 假设最多存储100个节点
}
~List()
{
delete[] data;
data = nullptr;
_size = 0;
};
// 头插法
void insert(int& a, int& b, string& c, double& d)
{
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 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 || (a == data[i].month && 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;
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);
}
double sum1 = 0;
int count1 = 0;
double sum2 = 0;
int count2 = 0;
for (int i = 0; i < L1._size; i++)
{
if (count1 >= n && count2 >= n)
break;
if (L1.data[i].name == "keyboard" && count1 < n)
{
sum1 += L1.data[i].price;
count1++;
}
else if (L1.data[i].name == "mouse" && count2 < n)
{
sum2 += L1.data[i].price;
count2++;
}
// 可以根据具体情况选择继续遍历或者跳出循环
//if (count1 >= n && count2 >= n)
// break;
//else continue;
//(这里注释掉的代码表示继续遍历,不注释表示遍历到第一个符合条件的节点后跳出循环)
}
cout << fixed << setprecision(1) << sum1 / n << endl;
cout << fixed << setprecision(1) << sum2 / n << endl;
return 0;
}
请注意,这只是一个简单的示例,仅仅将链表改为了顺序表,并未对代码进行完整的测试和优化。在实际应用中,还需要考虑更多因素,如动态扩容、插入位置是否合法等。
内容由零声教学AI助手提供,问题来源于学员提问




