Когда я вставляю узел в соседний список, я не могу получить значение на графике

  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  }

Я хотел бы нажать Node в соседнем списке.

Когда я позвонил в Linsert без "Line24", программа работала хорошо и напечатала "1"

Но когда я включил Line24, компилятор сказал

ошибка сегментации (ядро сброшено)

Я не знаю, почему я не смог получить значение graph->adj[0]->vertex.

1 ответ

Решение

Ошибка происходит в функции 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.
}
Другие вопросы по тегам