How would I clear a linked list?

2019-06-02 11:27发布

I have been trying to write a shortest path algorithm, dijkstras algorithm, finding the shortest path for the first two vertices works just fine. I run into the problem while trying to clear a linked list and a priority queue.

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;

}

Along with these clear methods I tried to simply set root to NULL and I also tried traversing through the list and using the delete on each element. I am having to luck with any of these methods. Root keeps getting set to an invalid location and I get access violation errors.

Is there something simple that I am just not seeing? How would I go about deleting every element from a linked list?

2条回答
聊天终结者
2楼-- · 2019-06-02 12:14

You need to go over each element and delete it Pseudo Code

Set pointer to root
While(pointer !=null)
{
  temp=pointer->next;
  delete[] pointer;
  pointer = temp;
}
查看更多
狗以群分
3楼-- · 2019-06-02 12:14

Setting root to NULL will delete the whole list.

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

You said you tried this. How is your access violation happening in this scenario?

Beware: my code probably contains a memory leak! You will probably want to walk through the list and deallocate each item, unless their memory is recovered using some other mechanism.

查看更多
登录 后发表回答