ZBLOG

使用单链表实现此代码:#include #include #include #include #include #include using namespace std; struct Record { int month; int day; string product; double price; }; bool compare(Rec...

以下是使用单链表实现给定代码的示例:

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>

using namespace std;

struct Record {
    int month;
    int day;
    string product;
    double price;
    
    Record* next; // 单链表指针
};

bool compare(Record a, Record b) {
    if (a.month == b.month) {
        return a.day > b.day;
    } else {
        return a.month > b.month;
    }
}

int main() {
    int m, n;
    cin >> m >> n;

    // 创建头结点
    Record* head = new Record();
    
    // 输入记录信息并构建单链表
    for(int i = 0; i < m; i++) {
        char slash;
        
        // 创建新节点
        Record* node = new Record();
        
        cin >> node->month >> slash >> node->day >> node->product >> node->price;

        // 将新节点插入到链表中
        node->next = head->next;
        head->next = node;
    }
    
    sort(records.begin(), records.end(), compare);
    
    map<string, vector<double>> productPrices;

   // 遍历单链表,按产品名称存储价格数据
   Record* current = head->next; 
   while(current != NULL) {
       if(productPrices[current->product].size() < n) {
           productPrices[current->product].push_back(current->price);
       }

       current = current->next; // 指向下一个节点
   }

   delete head; // 释放头结点内存

   for(auto& product : productPrices) {
       double sum = 0;
       for(auto& price : product.second) {
           sum += price;
       }
       cout << fixed << setprecision(1) << sum / product.second.size() << endl;
   }

   return 0;
}

请注意,此处只是将给定的代码进行了修改以使用单链表存储数据。可能还需要对其进行进一步的测试和调试,以确保正确性和稳定性。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?