How would I clear a linked list?

2019-06-02 11:31发布

问题:

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?

回答1:

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;
}


回答2:

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.