实现加权图时出现问题[c ++]

时间:2018-12-02 12:47:25

标签: c++ algorithm data-structures graph

我是编程的新手,我尝试使用带有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;
}

1 个答案:

答案 0 :(得分:1)

我认为根本问题是这样的:

newNode->next = list[src].head;

list[src]未初始化,仅指向随机存储器。 当您执行@ rafix07提到的操作并默认使用nullptr对其进行初始化时,它将起作用。