Я новичок в программировании, и я попытался реализовать граф, используя список смежности с языком программирования C ++.
Загрузка данных графика, кажется, работает.Но у меня возникла проблема при попытке распечатать график: Segmentation fault: 11
.В частности, это происходит в вершине 57. Я думаю, что логика программы в порядке, но я не знаю, где ошибка.
Текстовый файл: data.txt
И исходный код:
//
// main.cpp
// Dijkstra
//
// Created by Ibrahim El Mountasser on 02/12/2018.
// Copyright © 2018 Ibrahim El Mountasser. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
const int SIZE = 201;
struct Node{
int data;
int weight;
struct Node* next;
};
struct LinkedList {
struct Node* head;
};
class Graph {
public: LinkedList list[SIZE];
public:
Graph(std::string fileName) {
std::ifstream infile(fileName);
if(!infile.is_open()) return;
std::string line;
int i = 0;
while ( i < SIZE && getline(infile, line) )
{
std::istringstream str(line);
int u;
int w;
str >> u;
if ( u > SIZE )
{
// Problem.
std::cout<<"u is too large!"<<std::endl;
exit(-1);
}
int v;
char c;
while ( str >> v >> c >> w)
{
if( u < v)
{
createEdge(u, v, w);
std::cout<<"createEdge("<<u<<","<<v<<","<<w<<");"<<std::endl;
}
}
}
}
Node* createNode(int data, int weight){
Node* newNode = new Node;
newNode->data = data;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
void createEdge(int src, int dist, int weight) {
Node* newNode = createNode(dist, weight);
newNode->next = list[src].head;
list[src].head = newNode;
newNode = createNode(src, weight);
newNode->next = list[dist].head;
list[dist].head = newNode;
}
void printGraph() {
for (int i=0; i<SIZE; i++) {
std::cout<<i;
Node* temp = list[i].head;
while (temp != NULL) {
std::cout<<" -> "<<temp->data<<","<<temp->weight; // <== segfault here
temp = temp->next;
}
std::cout<<std::endl;
}
}
};
int main() {
Graph gr("data.txt");
gr.printGraph(); // <========= segfault when calling this
return 0;
}