如何删除循环双向链表中的所有节点?

时间:2018-11-12 13:13:32

标签: c++

我遇到了一个问题,因为我不知道如何删除此类列表中的所有节点。 您如何看待我的解决方案?调试器向我显示了一个问题“(...)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);

2 个答案:

答案 0 :(得分:0)

List *y = ptr;
delete y;
ptr = ptr->next;

在ptr分配的内存在delete y之后消失了。您无法调用ptr->next,因为ptr此时悬而未决,取消引用它是未定义的行为。尝试重新排列最后两行,即

ptr = ptr->next;
delete y;

答案 1 :(得分:0)

这是测试的完整示例

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