ZBLOG

使用c++将该代码改为使用顺序表实现 #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...

使用顺序表实现的代码如下所示:

  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* data;
  21. List(int capacity = 100) : _size(0)
  22. {
  23. data = new LNode[capacity];
  24. }
  25. ~List()
  26. {
  27. delete[] data;
  28. }
  29. // 在指定位置插入元素
  30. void insert(int index, int a, int b, string c, double d)
  31. {
  32. if (index < 0 || index > _size)
  33. {
  34. return;
  35. }
  36. for (int i = _size; i > index; i--)
  37. {
  38. data[i] = data[i - 1];
  39. }
  40. data[index].month = a;
  41. data[index].day = b;
  42. data[index].name = c;
  43. data[index].price = d;
  44. _size++;
  45. }
  46. void print_L()
  47. {
  48. for (int i = 0; i < _size; i++)
  49. {
  50. cout << data[i].month << " " << data[i].day << " ";
  51. }
  52. cout << endl;
  53. }
  54. int located(int a, int b)
  55. {
  56. for (int i = 0; i < _size; i++)
  57. {
  58. if (a < data[i].month || (a == data[i].month && b <= data[i].day))
  59. {
  60. return i + 1;
  61. }
  62. }
  63. return _size + 1;
  64. }
  65. };
  66. int main()
  67. {
  68. int m, n;
  69. string str;
  70. string c;
  71. double d;
  72. cin >> m >> n;
  73. List L1(m);
  74. for (int i = 0; i < m; i++)
  75. {
  76. cin >> str >> c >> d;
  77. int a = stoi(str, 0, 10);
  78. if (a >= 10)
  79. str.erase(0, 3);
  80. else
  81. str.erase(0, 2);
  82. int b = stoi(str, 0, 10);
  83. int e = L1.located(a, b);
  84. L1.insert(e - 1, a, b, c, d);
  85. }
  86. double sum1 = 0;
  87. int count1 = 0;
  88. double sum2 = 0;
  89. int count2 = 0;
  90. for (int i = 0; i < L1._size; i++)
  91. {
  92. if (count1 >= n)
  93. {
  94. break;
  95. }
  96. else
  97. {
  98. if (L1.data[i].name == "keyboard")
  99. {
  100. sum1 += L1.data[i].price;
  101. count1++;
  102. }
  103. }
  104. if (count2 >= n)
  105. {
  106. break;
  107. }
  108. else
  109. {
  110. if (L1.data[i].name == "mouse")
  111. {
  112. sum2 += L1.data[i].price;
  113. count2++;
  114. }
  115. }
  116. }
  117. cout << fixed << setprecision(1) << sum1 / n << endl;
  118. cout << fixed << setprecision(1) << sum2 / n << endl;
  119. return 0;
  120. }

这个版本使用了顺序表来实现链表的功能,包括插入、定位和打印等操作。注意,顺序表的容量是在创建对象时指定的,默认为100。如果需要处理更多的数据,请适当调整容量大小。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?