微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

释放邻接表

如何解决释放邻接表

作为一项作业,我必须编写一个代码,以给定的概率生成一个随机图,并检查直径。 我创建了一个函数,它调用 bfs V 次(V 是顶点数),让每个顶点成为起始顶点并存储它找到的最大路径。 之后,我必须为 10 个不同的概率运行代码 500 次(总共 5000 次) 我的代码使用了 3GB 并崩溃了,在某个时候它说一个指针为空,在为它分配内存后有一个生命,我猜这意味着 PC 物理上用完了空间来分配。 每次迭代后我都会把我写的函数放在释放邻接列表中,是不是我做错了什么?

图由一个结构体数组表示,这个数组表示图的顶点。 如果一个顶点确实有任何东西与之相连,那么数组的相同索引将指向一个包含所有邻居的链表。

我将按以下顺序包含这些功能: 数组结构 由数组指向的链表结构。 主函数中的数组声明。 边创建函数 释放图形的函数

//Struct for array:
typedef struct List
{
int vertex;
Node* head; 
}List;

//struct for linked lists pointed to by array:
typedef struct Node
{
int e;
struct Node* next; 
}Node;

//declaration for array of vertices:
List** vertices = (List*)calloc(v,sizeof(List));

//function that builds random graph,and uses "add edge" to create one if 
needed
int build_random_graph(int v,float p,List** vertices) 
{                                                      
int i,j;
for (i = 0; i < v; i++)
{
    vertices[i] = malloc(sizeof(List)); //Creating array of vertices.
    vertices[i]->head = NULL;
    vertices[i]->vertex = i;
}
srand(time(0)); 
for (i = 0; i < v; i++)
{
    for (j = 0; j < v; j++)
    {
        if ((j > i) && (rand() / (double)RAND_MAX <= p)) 
        {                                                
            add_edge(i,j,vertices);                    
        }
    }
}
}


//Function for edge creation:
int add_edge(int i,int j,List** vertices) 
{
Node* dest;
Node* src;
Node* temp;
if (vertices[i]->head == NULL)
{
    src = malloc(sizeof(Node));
    src->e = j;
    src->next = NULL;
    vertices[i]->head = src;
}
else
{
    dest = malloc(sizeof(Node));
    dest->e = j; //Each time. this is where the error occurs.
    dest->next = NULL;
    temp = vertices[i]->head;
    while (temp->next)
    {
        temp = temp->next;
    }
    temp->next = dest;
    
}

if (vertices[j]->head == NULL)
{
    src = malloc(sizeof(Node));
    src->e = i;
    src->next = NULL;
    vertices[j]->head = src;
}
else
{
    dest = malloc(sizeof(Node));
    dest->e = i;
    dest->next = NULL;
    temp = vertices[j]->head;
    while (temp->next)
    {
        temp = temp->next;
    }
    temp->next = dest;
    
}

//Freeing the graph:
void freelist(int v,List** vertices)
{

int i;
for (i = 0; i < v; i++)
{
    Node* t = vertices[i]->head;
    Node* p;
    while (t->next != NULL)
    {
        p = t;
        t = t->next;
        free(p);
    }
    free(t);
}
for (i = 0; i < v; i++)
{
    List* ptr;
    ptr = vertices[i];
    free(ptr);
}
free(vertices);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。