如何清除链表? [英] How would I clear a linked list?
问题描述
我一直在试图写一个最短路径算法,dijkstras算法,找到前两个顶点的最短路径工作就好了。在尝试清除链接列表和优先级队列时遇到问题。
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;
}
除了这些明确的方法, NULL,我也试过遍历列表和使用删除每个元素。我必须运气这些方法。 Root不断设置为无效位置,并且我遇到访问冲突错误。
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?
推荐答案
您需要浏览每个元素并删除它
伪代码
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;
}
这篇关于如何清除链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!