Endlessloop同时用指针清除队列

时间:2018-02-20 19:52:16

标签: c++

我有一个LastTimeOn结构,它具有指向同一结构的下一个指针。我不想介绍后退指针。我正在努力清理这个结构,你可以帮帮我吗?在泵上可以打开多次,然后结构像这个泵1 - > lastTimeOn-> gt> next-> next-> next一样增长。该程序以无限循环REM2REM3REM4REM2REM3REM4等运行:

class Pump {
public:
    LastTimeOn *lastTimeOn;
    Pump();
};

class LastTimeOn{
public:
    unsigned int dayOfWeek;
    unsigned int hour;
    unsigned int minute;
    LastTimeOn(unsigned int minute1, unsigned int hour1, unsigned int dayOfWeek1);
    LastTimeOn *next;
};

void clearLastTimeOn(Pump *pump1) {
    Serial.print("REM1");
    while (pump1->lastTimeOn != NULL) {
        LastTimeOn *lastTimeOn = pump1->lastTimeOn;
        Serial.print("REM2");
        while (lastTimeOn->next != NULL) {
            Serial.print("REM3");

            lastTimeOn = lastTimeOn->next;

        }
        Serial.print("REM4");
        delete lastTimeOn;
        if (pump1->lastTimeOn->next == NULL){
            Serial.print("REM4a");
            delete pump1->lastTimeOn;
            pump1->lastTimeOn = NULL;
        }
    }
    Serial.print("REM5");
}

我创建了这样的新数据:

lastTimeOn->next = new LastTimeOn(minute, hour, dayOfWeek);

2 个答案:

答案 0 :(得分:2)

我得到了一个简单的想法......你将你的pump1-> lastTimeOn传递给了:

void clearLastTimeOn(LastTimeOn* lastTimeOn)
{
    while (lastTimeOn != nullptr)
    {
        LastTimeOn* current = lastTimeOn;
        lastTimeOn = lastTimeOn->next;
        delete current;
    }
}

然后将pump1-> lastTimeOn设置为nullptr。

答案 1 :(得分:1)

class LastTimeOn{
public:
    unsigned int dayOfWeek;
    unsigned int hour;
    unsigned int minute;
    LastTimeOn(unsigned int minute1, unsigned int hour1, unsigned int dayOfWeek1);
    LastTimeOn();
    LastTimeOn *next;
    ~LastTimeOn() { delete this->next; }
};

void clearLastTimeOn(Pump *pump1) {
    if (pump1)
       delete pump1->lastTimeOn;
}