ZBLOG

使用顺序表等其他方法修改此代码:#ifndef NULL #define NULL 0 #endif #include #include #include using namespace std; struct LNode { //存储数据 int month; int day; string name; double price; LNode* next;//后继指针 LNode() {}; LNode(int a,...

下面是使用顺序表修改后的代码:

  1. #ifndef NULL
  2. #define NULL 0
  3. #endif
  4. #include<iostream>
  5. #include<iomanip>
  6. #include<string>
  7. using namespace std;
  8. struct LNode
  9. {
  10. //存储数据
  11. int month;
  12. int day;
  13. string name;
  14. double price;
  15. };
  16. class List
  17. {
  18. public:
  19. int _size;
  20. LNode* arr;
  21. void init() {
  22. arr = new LNode[100]; // 假设最大容量为100
  23. for (int i = 0; i < 100; i++) {
  24. arr[i].month = -1; // 初始化月份为-1,表示该位置为空
  25. }
  26. _size = 0;
  27. }
  28. List() { init(); } // 构造函数
  29. ~List() { delete[] arr; }; // 析构函数
  30. void insert(int& a, int& b, string& c, double& d)
  31. {
  32. if (_size >= 100) return; // 容量已满
  33. _size++;
  34. int index = _size - 1;
  35. while (index > 0 && (a < arr[index - 1].month || (a == arr[index - 1].month && b < arr[index - 1].day))) {
  36. arr[index] = arr[index - 1];
  37. index--;
  38. }
  39. arr[index].month = a;
  40. arr[index].day = b;
  41. arr[index].name = c;
  42. arr[index].price = d;
  43. }
  44. };
  45. int main()
  46. {
  47. int m, n;
  48. string str;
  49. string c;
  50. double d;
  51. List L1;
  52. double ave1 = 0.0;
  53. double ave2 = 0.0;
  54. cin >> m >> n;
  55. for (int i = 0; i < m; i++)
  56. {
  57. cin >> str >> c >> d;
  58. int a = stoi(str, 0, 10);
  59. if (a >= 10)
  60. str.erase(0, 3);
  61. else
  62. str.erase(0, 2);
  63. int b = stoi(str, 0, 10);
  64. L1.insert(a, b, c, d);
  65. }
  66. double sum1 = 0.0;
  67. int count1 = 0;
  68. double sum2 = 0.0;
  69. int count2 = 0;
  70. for (int i = 0; i < L1._size; i++)
  71. {
  72. if (count1 >= n && count2 >= n)
  73. {
  74. break;
  75. }
  76. if (L1.arr[i].name == "keyboard" && count1 < n)
  77. {
  78. sum1 += L1.arr[i].price;
  79. count1++;
  80. }
  81. if (L1.arr[i].name == "mouse" && count2 < n)
  82. {
  83. sum2 += L1.arr[i].price;
  84. count2++;
  85. }
  86. }
  87. cout << fixed << setprecision(1) << sum1 / n << endl;
  88. cout << fixed << setprecision(1) << sum2 / n << endl;
  89. return 0;
  90. }

使用顺序表进行了修改,将链表改为数组存储数据,并对插入操作做了相应的调整。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9585

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?