当我在相邻列表中插入节点时,我无法在图表上获得价值
When I insert node in adjacent list, I couldn't get value on the graph
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.
}
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.
}