c++ - 如何循环链表以减少值?

标签 c++ class function linked-list singly-linked-list

我有一个名为 SensorNode 的类,其中包含(除其他外)传感器对象的链接列表。节点有一个数据成员表示它剩余的电池电量,每个传感器都有一个数据成员表示它们消耗了多少电量。我有一个名为 processTimeClick 的函数,它应该遍历节点中传感器的整个链接列表,并从节点剩余的电池中减去它们使用的电量。不幸的是,我收到“错误,错误的访问代码”,我不知道为什么。这是我的功能,我希望有人能看到我的逻辑哪里错了。

void SensorNode::processTimeClick() {
    if (batt == 0) {

    }
    else {
        temp = mySensors;
        do {
            if (batt <=0) {
                cout << "\nThis node has run out of battery\n";
                func = 0;
                break;
            }
            batt = (batt - (temp->SensEl->getPC()));
            temp = temp->LLelement;

        } while (temp->LLelement != NULL); //My code stops here and says "Thread   1:EXC_BAD_ACCESS (code=1, address=0x0)
        }
    }

为了更容易理解: temp 和 mySensors 都是“SensorBlock”类型(即链表对象)的指针(在 SensorNode 类中声明)。 batt 是 SnesorNode 类中的 float 数据成员。

这是 SensorBlock 类的声明:

class SensorBlock {

    friend class SensorNode;
    SensorBlock * LLelement;
    sensor * SensEl;
    SensorBlock(sensor* senspoint);
};
SensorBlock::SensorBlock(sensor* senspoint) {
    SensEl = senspoint;
    LLelement = NULL;
}

感谢您的帮助!

最佳答案

我想你希望你的循环看起来更像这样:

    while (temp) {
        if (batt <=0) {
            cout << "\nThis node has run out of battery\n";
            func = 0;
            break;
        }
        batt = (batt - (temp->SensEl->getPC()));
        temp = temp->LLelement;

    }

这样,在您尝试使用 temp 之前检查它以确保它不为空。

如果你有这样一个循环:

do {
  // use temp
  temp = temp->LLelement;
} while (temp->LLelement);

相当于

beginning_of_loop:
  // use temp -- oops it might be null!
  temp = temp->LLelement;
  // temp might be null here
  if (temp->LLelement) goto beginning_of_loop;

如果将 while 放在顶部,则相当于:

beginning_of_loop:
  if (!temp) goto end_of_loop:
  // use temp -- can't be null
  temp = temp->LLelement;
  // temp might be null here, but we aren't using it
  goto beginning_of_loop;
end_of_loop:

关于c++ - 如何循环链表以减少值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17013249/

相关文章:

c++ - 字符串包含有效字符

python - 在不复制代码的情况下访问函数中声明的所有变量

python - 一个属性可以访问另一个属性吗?

jquery - 使用 jQuery 检测 iPhone 滑动

python - 是否有更 Pythonic 的方式通过字符串名称访问函数?

c++ - 三维数组的下标是否严格定义?

c++ - 确定哪些目标文件导致 .dll 大小增加 [C++]

c++ - C++ 初级/中级项目?

c++ - 在 C++ 类方法中使用 *this 完全覆盖自实例化

javascript - 将 <img class> 图像链接到 URL - 在 safari 和 chrome 中工作正常,但在 Firefox 中不行