[英]How to delete all nodes in circular doubly linked list?
I've got a problem, because I don't know how to delete all nodes in that kind of list. 我遇到了一个问题,因为我不知道如何删除此类列表中的所有节点。 What do you think about my solution?
您如何看待我的解决方案? Debugger shows me a problem "(...) x was 0xDDDDDDDD"
调试器向我显示了一个问题“(...)x为0xDDDDDDDD”
void del(List *&head) {
List* ptr = head;
List* help;
do {
List *x = ptr;
List *y = ptr;
x = y;
help = x;
x = x->next;
delete y;
head = NULL;
ptr = ptr->next;
} while (help!=NULL);
List *y = ptr;
delete y;
ptr = ptr->next;
The memory allocated at ptr is gone after delete y
. delete y
之后,分配给ptr的内存将消失。 You can not call ptr->next
as ptr is dangling at this point and de-referencing it is undefined behavior. 您无法调用
ptr->next
因为此时ptr ptr->next
,取消引用它是未定义的行为。 Try reordering the last two lines ie 尝试重新排序最后两行,即
ptr = ptr->next;
delete y;
Here is the complete example with the test 这是测试的完整示例
struct Node
{
Node(Node* prev, int val)
: prev(prev), next(NULL), value(val)
{ }
Node *prev, *next;
int value;
};
void clear_list(Node*& head)
{
if (head != NULL)
{
Node* curr = head->next;
while (curr != NULL && curr != head)
{
std::cout << "Deleting " << curr->value << std::endl;
Node* temp = curr;
curr = curr->next;
delete temp;
};
delete head;
head = NULL;
}
}
void print_list(Node*& head)
{
if (head != NULL)
{
Node* curr = head;
do
{
std::cout << (curr == head ? "Head: " : "") << curr->value << std::endl;
curr = curr->next;
} while (curr != NULL && curr != head);
}
}
int main()
{
Node* head = new Node(NULL, 0);
Node* curr = head;
for (int i = 1; i <= 10; i++)
{
Node* prev = curr;
curr = new Node(prev, i);
prev->next = curr;
}
// Link end to head
curr->next = head;
//
print_list(head);
clear_list(head);
print_list(head);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.