【问题标题】:How to add something to a linked list如何向链表添加内容
【发布时间】:2013-06-02 19:50:03
【问题描述】:

我只是对我遇到的一个错误有点困惑。我创建了一个名为“SensorNode”的类,每个 SensorNode 都有一个传感器链接列表。 SensorNode 的一个数据成员是一个名为 mySensors 的 SensorBlock(链表)指针。 mySensors 应该指向它所在的传感器节点所拥有的传感器链表中的第一个传感器。这是 SensorNode 的类声明:

class SensorNode {
    char* NodeName;
    int NodeID;
    LOCATION Node1;
    float batt;
    int func;
    SensorBlock *mySensors;


public:
    SensorNode(char *n, float x, float y, float z, int i, float ah);
    void print();
    void setOK(int o);
    int getOK();
    void setLOC(float longi, float lat, float h);
    int amIThisSensorNode(char *n);
    void addSensorToNode(sensor *s);
};

这是 SensorBlock 的类声明:

class SensorBlock {

    friend class SensorNode;
    SensorBlock * LLelement;
    sensor * SensEl;
};

我的问题在于我的 void addSensorToNode(sensor *s) 函数。参数 s 指向一个传感器,该传感器应该被添加到属于该节点的传感器列表的末尾。而且我不知道该怎么做,因为它不是我正在创建和添加的新传感器,而是指向我正在添加的传感器的指针。

这是我目前所拥有的:

void SensorNode::addSensorToNode(sensor *s) {
    if(mySensors == '\0') //mySensors is first initialized to NULL
    {
        mySensors = s; //I get an error on this line.
    }
    else {

    }
}

我不知道如何修复我在上面那一行中遇到的错误,并且当 mySensors 不再等于 null 时,我不知道在“else”中输入什么。如果我解决了上述错误,我可能能够更好地理解新传感器的添加过程。提前感谢您提供的任何帮助!

【问题讨论】:

    标签: c++ class pointers linked-list memory-address


    【解决方案1】:

    mySensors = s 应该是mySensors.SensEl= s

    因为 mySensors 的类型是 SensorBlock 而 s 是 sensor

    void SensorNode::addSensorToNode(sensor *s) {
        if(mySensors == NULL) //mySensors is first initialized to NULL
        {
            mySensors = new SensorBlock();
            mySensors->SensEl = s; //I get an error on this line.
            mySensors->LLelement = NULL;
        }
        else {
    
           SensorBlock newBlock = new SensorBlock();
           newBlock->SensEl = s;
           newBlock->LLelement = NULL;
           mySensors->LLelement = newBlock;
    
        }
    }
    

    【讨论】:

    • 磕头菜鸟失误,我一定累了,谢谢。我认为它实际上需要是 mySensors->SensEl = s;但同样的基本思想。谢谢你指出来
    • 如果它不是链表的最开始,我应该在 else 中放什么?
    • @Acoustic,编辑了答案,但我认为您可以通过统一传感器类和 SensorBlock 来简化数据结构
    • ^感谢您添加 else 语句的内容!不幸的是,我收到一个错误:“没有从 'SensorBlock *' 到 'SensorBlock' 的可行转换”。知道这意味着什么吗?您对统一的看法是正确的,但不幸的是,这是一项作业,我无法更改课程:/
    猜你喜欢
    • 2015-11-27
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多