使用顺序表实现的代码如下所示:
#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(int capacity = 100) : _size(0)
{
data = new LNode[capacity];
}
~List()
{
delete[] data;
}
// 在指定位置插入元素
void insert(int index, int a, int b, string c, double d)
{
if (index < 0 || index > _size)
{
return;
}
for (int i = _size; i > index; i--)
{
data[i] = data[i - 1];
}
data[index].month = a;
data[index].day = b;
data[index].name = c;
data[index].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;
cin >> m >> n;
List L1(m);
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 - 1, 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)
{
break;
}
else
{
if (L1.data[i].name == "keyboard")
{
sum1 += L1.data[i].price;
count1++;
}
}
if (count2 >= n)
{
break;
}
else
{
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;
}
这个版本使用了顺序表来实现链表的功能,包括插入、定位和打印等操作。注意,顺序表的容量是在创建对象时指定的,默认为100。如果需要处理更多的数据,请适当调整容量大小。
内容由零声教学AI助手提供,问题来源于学员提问