在c ++中删除链接列表数组

问题描述 投票:0回答:1

我创建了存储桶以插入我的数据,除了删除所有节点外,其他所有操作都正常。如果使用delete[] container删除容器,则仅删除所有链接列表的第一个节点。我认为我所做的是合乎逻辑的,但没有用。您能告诉我为什么吗?(​​仅关注函数的最后一个循环,其他代码位可供参考。)

void createBucket(int* arr, int l, int r){
    int max = findMax(arr, l, r);
    int digits = findDigit(max);
    int divide = pow(10, digits-1);
    int maxPos = max/divide;
    int pos;//position of elements in the container
    bucket* container = new bucket[maxPos+1];
    bucket* cursor;
    //copying elements to their respective buckets
    for(int i=l; i<=r; i++){

        pos = arr[i]/divide;

        if(container[pos].val == 0){
            container[pos].val = arr[i];
            container[pos].next = NULL;
        }
        else{
            bucket* node = new bucket;
            cursor = &container[pos];
            node->val = arr[i];
            while(cursor->next!=NULL){
                cursor = cursor->next;
            }
            cursor->next = node;
            node->next = NULL;
        }
    }
    //copying the elements from the buckets to their respective position
    int j = 0;
    for(int i = 0; i<maxPos+1; i++){
        cursor = &container[i]; 
        while(cursor!=NULL && cursor->val!=0){
            arr[j] = cursor->val;
            cursor = cursor->next;
            j++;
        }
    }
    //deleting all nodes
    bucket* tmp;
    for(int i= 0; i<maxPos+1; i++){
        cursor = &container[i];
        while(cursor!=NULL){
            tmp = cursor;
            cursor = cursor->next;
            delete tmp;
        }
    }
}

它发出如下错误:

double free or corruption (out)
Aborted (core dumped)
c++ singly-linked-list
1个回答
-1
投票

似乎您的链表本身不是在管理内存。相反,链接列表的节点仅指向container内部的内存。

您可以仅通过删除用于管理内存的容器来删除所有节点

delete [] container;
© www.soinside.com 2019 - 2024. All rights reserved.