gpt4 book ai didi

c - 在邻接表中使用 DFS 并使用指针的指针数组

转载 作者:行者123 更新时间:2023-11-30 17:04:16 25 4
gpt4 key购买 nike

我正在尝试创建一个 C 程序,该程序读取一个输入文件,该文件包含一组表示无向图边缘的点。我试图将每个顶点结构存储在使用指针实现的数组中,但是该数组在 load_file 运行后并不保存所有顶点,它只包含第一个顶点。我也不确定如何实现 DFS 来查找每个顶点和顶点 1 之间的边数。目前底部函数是发生此逻辑的地方,但我不知道该怎么做。

#include <stdio.h>
#include <stdlib.h>
#include "../HW3/input_error.h"
#define VertexToSearch 1

typedef struct node {
int value;
struct node* nextedge;
}edge;

typedef struct node1 {
int vertexnumber;
int distance;
edge* edge;
} vertex;


vertex* load_file(char*, vertex*);
vertex* create_vertex_list(vertex*, int*);
vertex* create_new_edge(int*, int*, vertex*);
void print_distance(vertex*);
vertex* find_vertex(vertex*,int);
enum error program_error;

int main(int argc, char** argv) {
vertex* array;
array = load_file(argv[1], array);
print_distance(array);
}

vertex* load_file(char* filename, vertex* head) {

int* count = malloc(sizeof (int));
int* vertex1 = malloc(sizeof (int));
int* vertex2 = malloc(sizeof (int));
FILE* file = fopen(filename, "r");

if (file == NULL) {
printf("%s did not open", filename);
program_error = FILE_FAILED_TO_OPEN;
exit(program_error);
}

fscanf(file, "%d", count);
head = malloc(sizeof(vertex)* *count);
head = create_vertex_list(head, count);
for (int i = 0; i<*count; i++) {
fscanf(file, "\n(%d,%d)", vertex1, vertex2);
head = create_new_edge(vertex1, vertex2, head);
}

free(count);

free(vertex1);
free(vertex2);
fclose(file);

return head;
}

vertex* create_vertex_list(vertex* head, int* count) {
vertex *new_node, *current;
for (int i = 0; i<*count; i++) {
new_node = malloc(sizeof (vertex));
new_node->vertexnumber = i + 1;
new_node->edge = NULL;
new_node->distance = 0;

head[i] = *new_node;
}
return head;
}

vertex* create_new_edge(int* vertex1, int* vertex2, vertex* head) {
edge* new = malloc(sizeof (edge));
edge* new1 = malloc(sizeof (edge));
new->value = *vertex1;
new1->value = *vertex2;
new->nextedge = NULL;
new->nextedge = NULL;

head[*vertex1].edge = new1;
head[*vertex2].edge = new;

return head;
}
void print_distance(vertex* head){
while(head != NULL){
if(head->edge->value == VertexToSearch){
printf("found");
}
head++;
}
while(head != NULL){
printf("%d %d\n",head->vertexnumber,head->distance);
head++;
}
}

最佳答案

除了内存泄漏

new_node = malloc(sizeof (顶点));
边缘* new = malloc(sizeof (边缘));
边缘* new1 = malloc(sizeof (边缘));

你的打印功能永远无法工作。 head++ 永远不会变成 NULL。

关于c - 在邻接表中使用 DFS 并使用指针的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com