gpt4 book ai didi

c - 当我在相邻列表中插入节点时,我无法在图表上获取值

转载 作者:行者123 更新时间:2023-11-30 14:56:45 25 4
gpt4 key购买 nike

  6 typedef struct _Node{
7 int vertex;
8 struct _Node * next;
9 }Node;
10
11 typedef struct _graph{
12 Node *adj[MAX_TERMS];
13 }Graph;
14
15 void Linsert(Graph * graph, int count, Node * temp)
16 {
17 Node * cur = graph->adj[count];
18
19 while(cur != NULL)
20 cur = cur->next;
21
22 cur = temp;
23 printf("%d\n", temp->vertex);
24 printf("%d\n", (graph->adj[0])->vertex);
25 }
26


27 int main()
28 {
29 FILE * fp = fopen("input.txt", "r");
30 int n, vertex;
31 int count = 0;
32 Graph * graph;
33 fscanf(fp, "%d", &n);
34
35 graph = (Graph*)malloc(sizeof(Graph));
36
37 for(int i = 0; i < n; i++)
38 graph->adj[i] = NULL;
39
40 Node * temp = (Node*)malloc(sizeof(Node));
41 temp->vertex = 1; temp->next = NULL;
42 Linsert(graph, 0, temp);
43 }

我想将节点推送到相邻列表中。

当我在没有“Line24”的情况下调用 Linsert 时,程序运行良好并打印“1”

但是当我包含 Line24 时,编译器说

segmentation fault(core Dumped)

我不知道为什么我无法获取值图->adj[0]->顶点。

最佳答案

函数 Linsert() 发生错误,代码应该是这样的:

void Linsert(Graph * graph, int count, Node * temp) {
if (!graph->adj[count]) {
graph->adj[count] = temp;
return ;
}
cur = graph->adj[count];
while (cur->next != NULL) {
cur = cur->next;
}
// then cur is the final nodes of the graph[count]
cur->next = temp;
temp->next = NULL; // I suggest the phrase to be used in constructor.
}

关于c - 当我在相邻列表中插入节点时,我无法在图表上获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448461/

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