我该如何清除链表?

Bea*_*180 1 c++ pointers linked-list clear shortest-path

我一直在尝试编写一个最短路径算法,dijkstras算法,找到前两个顶点的最短路径工作正常.我在尝试清除链表和优先级队列时遇到了问题.

class llNode {
public:
    int id;
    int source;
    int weight;
    llNode* next;
    llNode(int key, int distance, int from) {
        id=key;
        weight=distance;
        source=from;
        next = NULL;
    }
};


class lList {
private:
    llNode* root;
    llNode* end;

    void clearAll(llNode* toClear);


public:
    lList() {
        root = NULL;
    }

    void add(llNode* toAdd) {
        if ( root == NULL) {
            root = toAdd;
            end = toAdd;
            return;
        }

        end->next = toAdd;
        end=end->next;
    }

    bool isFound(int key) {
        for(llNode* ii= root; ii != NULL ; ii=ii->next) {
            if ( ii->id == key) {
                return true;
            }
        }

        return false;
    }

    void clearAll();

};

void lList::clearAll() {
clearAll(root);
}

void lList::clearAll(llNode* toClear) {
if(toClear == NULL) {
    return;
}

clearAll(toClear->next);

toClear=NULL;

}
Run Code Online (Sandbox Code Playgroud)

除了这些明确的方法,我试图简单地将root设置为NULL,我还尝试遍历列表并在每个元素上使用delete.我不得不运气这些方法.Root一直设置为无效位置,我收到访问冲突错误.

有什么简单的东西,我只是没有看到?如何删除链表中的每个元素?

Pep*_*epe 5

你需要遍历每个元素并删除它伪代码

Set pointer to root
While(pointer !=null)
{
  temp=pointer->next;
  delete[] pointer;
  pointer = temp;
}
Run Code Online (Sandbox Code Playgroud)