以下是使用顺序表进行修改后的代码:
#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* arr; // 使用数组代替链表存储节点信息
List() {
_size = 0;
arr = new LNode[100]; // 假设最大容量为100,可以根据实际需求进行调整
}
~List() {
delete[] arr;
};
//头插法
void insert(int& a, int& b, string& c, double& d)
{
for (int i = _size; i > 0; --i) {
arr[i] = arr[i - 1];
}
arr[0].month = a;
arr[0].day = b;
arr[0].name = c;
arr[0].price = d;
_size++;
}
int located(int a, int b)
{
for (int i = 0; i < _size; ++i) {
if (a < arr[i].month || (a == arr[i].month && b < arr[i].day)) {
return i + 1; // 返回插入位置,从1开始计数
}
}
return _size + 1; // 若没有找到合适的位置,则插入到末尾+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 < m; i++)
{
if (count1 >= n) {
break;
}
else {
if (L1.arr[i].name == "keyboard") {
sum1 += L1.arr[i].price;
count1++;
}
}
}
for (int i = 0; i < m; i++)
{
if (count2 >= n) {
break;
}
else {
if (L1.arr[i].name == "mouse") {
sum2 += L1.arr[i].price;
count2++;
}
}
}
cout << fixed << setprecision(1) << sum1 / n << endl;
cout << fixed << setprecision(1) << sum2 / n << endl;
return 0;
}
这里将链表改为使用数组实现顺序表的方式,同时进行相应的修改。注意,由于题目中并未规定具体的节点个数,这里假设最大容量为100,并使用了一个成员变量 _size
来记录当前元素个数。你可以根据实际需求进行调整。
内容由零声教学AI助手提供,问题来源于学员提问