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 = nullptr; // 链表头指针

    for(int i = 0; i < m; i++) {
        char slash;
        
        // 创建新节点
        Record* newNode = new Record();
        
        cin >> newNode->month >> slash >> newNode->day >> newNode->product >> newNode->price;

        newNode->next = head; // 将新节点插入链表头部
        head = newNode; // 更新链表头指针
    }
    
    sort(records.begin(), records.end(), compare);
    
    map<string, vector<double>> productPrices;

  	// 遍历链表进行处理
  	Record* current = head;
  	while(current != nullptr){
      	if(productPrices[current->product].size() < n) {
          	productPrices[current->product].push_back(current->price);
      	}
      	current = current->next; // 移动到下一个节点
  	}
  	
  	delete current; // 删除最后一个节点
    
    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=9704

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?