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, int b, string c...

将给定的代码修改为使用顺序表实现时,需要对链表的插入和遍历部分进行修改。顺序表是基于数组实现的线性表,可以通过数组下标来访问元素。

以下是将代码修改为使用顺序表实现的示例:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

struct LNode {
    // 存储数据
    int month;
    int day;
    string name;
    double price;
};

class List {
public:
    int _size;  // 当前元素个数
    int capacity;  // 顺序表容量
    LNode* data;  // 数据数组

public:
    List(int cap) : _size(0), capacity(cap), data(new LNode[cap]) {}
    ~List() { delete[] data; }

    void insert(int index, int a, int b, const string& c, double d) {
        if (index < 0 || index > _size) {
            return;
        }
        if (_size == capacity) {
            resize();  // 扩容
        }
        for (int i = _size - 1; i >= index; --i) {
            data[i + 1] = data[i];  // 元素后移
        }
        data[index].month = a;
        data[index].day = b;
        data[index].name = c;
        data[index].price = d;
        ++_size;
    }

private:
    void resize() {
        capacity *= 2;
        LNode* newData = new LNode[capacity];
        for (int i = 0; i < _size; ++i) {
            newData[i] = data[i];
        }
        delete[] data;
        data = newData;
    }
};

int main() {
    int m, n;
    string str, c;
    double d;

    cin >> m >> n;
    List L1(m);
    
    for (int i = 0; i < m; ++i) {
        cin >> str >> c >> d;
        int a = stoi(str.substr(0, 2));
        int b = stoi(str.substr(3, 2));
        
        int e = L1.located(a, b);
        L1.insert(e, a, b, c, d);
    }

    double sum1 = 0;
    int count1 = 0;
    double sum2 = 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
         << fixed << setprecision(1) << sum2 / n << endl;

    return 0;
}

请注意,顺序表的容量初始大小为m,并且在插入元素时需要检查是否需要进行扩容。另外,月份和日期的提取使用了substr函数来截取子字符串。顺序表的遍历直接通过数组下标进行访问。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?