我正在尝试实现图表的BFS。 这些是我的头文件 -
nodes.h
typedef struct Node
{
int data;
struct Node* next;
}Node;
typedef struct Queue
{
Node * front;
Node * rear;
}Queue;
control.h
#include"nodes.h"
Queue * CreateQueue();
int isEmptyQueue(Queue * Q);
void EnQueue(Queue * Q,int data);
int DeQueue(Queue * Q);
void DeleteQueue(Queue * Q);
这是我的代码,它实现了用于BFS(广度优先搜索)的队列。这在没有我的BFS代码的情况下运行时效果很好。但是使用BFS代码会产生内存分配错误(我在上面提到了我的错误)当我为CreateQueue()
分配内存时,函数Queue
中的最后一个问题。)
queue.c
#include<stdlib.h>
#include<stdio.h>
#include"control.h"
Queue * CreateQueue()
{
Queue * Q;
Node * temp;
Q=(Queue *)malloc(sizeof(Queue));printf("Hello\n");
if(!Q)
return NULL;
temp=malloc(sizeof(Node));
Q->front=Q->rear=NULL;
return Q;
}
int isEmptyQueue(Queue * Q)
{
return(Q->front==NULL);
}
void EnQueue(Queue * Q,int data)
{
Node * newNode;
newNode=malloc(sizeof(Node));
newNode->data=data;
newNode->next=NULL;
if(Q->rear)
Q->rear->next=newNode;
if(Q->front==NULL)
Q->front=Q->rear=newNode;
}
int DeQueue(Queue * Q)
{
int data;
Node * temp;
if(isEmptyQueue(Q))
return 0;
else
{
temp=Q->front;
data=Q->front->data;
Q->front=temp->next;
//free(temp);
}
return data;
}
这是我使用queue.c
BFS.c
#include<stdio.h>
#include<stdlib.h>
#include"control.h"
typedef struct Graph
{
int V;
int E;
int * visited;
int * vis;
int ** Adj;
}Graph;
Graph * adjMatrix()
{
int i,j,v2,v1;
Graph * G = (Graph *)malloc(sizeof(Graph));
FILE * input;
input=fopen("input.txt","r");
fscanf(input,"%d",&G->V);
fscanf(input,"%d",&G->E);
G->Adj = (int **)malloc(G->V * sizeof(int *));
G->visited = (int *)malloc(G->V * sizeof(int ));
G->vis = (int *)malloc(G->V * sizeof(int ));
for (i=1; i<=G->V; i++)
G->Adj[i] = (int *)malloc(G->V * sizeof(int));
for(i=1;i<=G->V;i++)
{
for(j=1;j<=G->V;j++)
{
G->Adj[i][j]=0;
}
}
fscanf(input,"%d %d",&v1,&v2);
while(!feof(input))
{
G->Adj[v1][v2]=1;
G->Adj[v2][v1]=1;
fscanf(input,"%d %d",&v1,&v2);
}
return G;
}
void BFS(Graph * G,int u)
{
int i;
Queue * Q=CreateQueue();
EnQueue(Q,u);
while(!isEmptyQueue(Q))
{
u=DeQueue(Q);
printf("%d\n",u);
//Process v
G->visited[u]=1;
for(i=1;i<=G->V;i++)
{
if(!G->visited[i] && G->Adj[u][i]==1)
EnQueue(Q,i);
}
}
}
int main()
{
Graph * G=adjMatrix();
int i,j,k,count=0;
//Display the graph
for(i=1;i<=G->V;i++)
{
for(j=1;j<=G->V;j++)
printf("%d ",G->Adj[i][j]);
printf("\n");
}
BFS(G,3);
}
我正在使用矩阵表示并从文件中获取输入。代码是正确的,当我在BFS中调用CreateQueue
时出现问题。我得到运行时错误 -
错误
exe: malloc.c:2369: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
Aborted (core dumped)
任何帮助都将受到高度赞赏。谢谢。