以下是使用顺序表(数组)实现的代码:
#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; // 使用动态数组代替链表
void init()
{
data = new LNode[100]; // 假设最大容量为100,可以根据需求调整大小
_size = 0;
}
List() { init(); } // 构造函数
~List()
{
delete[] data; // 删除动态数组内存空间
};
// 头插法
void insert(int a, int b, string c, double d)
{
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 < 1 || index > _size + 1) 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)
{
e++;
continue;
}
else if (a > data[i].month)
{
return e;
}
if (b < data[i].day)
{
e++;
continue;
}
else if (b > data[i].day)
{
return e;
}
return e; // 如果找到匹配的月份和日期,则返回位置
}
return e; // 如果没有找到匹配的月份和日期,返回位置也是在最后
};
};
int main()
{
int m, n;
string str, c;
double d;
List L1;
double ave1 = 0.0, ave2 = 0.0;
cin >> m >> n;
for (int i = 0; i < m; i++)
{
cin >> str >> c >> d;
int a = stoi(str.substr(2), nullptr);
int b = stoi(str.substr(0, 2), nullptr);
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; i++)
{
if (count1 >= n)
{
break;
}
else
{
if (L1.data[i].name == "keyboard")
{
sum1 += L1.data[i].price;
count1++;
}
}
}
for (int i = 0; i < m; i++)
{
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;
}
请注意,该代码是通过将链表更改为动态数组(顺序表)实现的。
内容由零声教学AI助手提供,问题来源于学员提问