图表的链接列表实现

时间:2015-05-20 00:52:55

标签: c++ graph-theory

我对C ++很陌生。

我尝试使用链接节点创建图表的邻接列表实现,在视觉上它看起来像这样:

[Headnode Vertex | Next Node] -> [Adjacent Node Vertex | Next] -> etc
[0 | ]-> [1 | ]-> [2 | ]-> [NULL node]
[1 | ]-> [0 | ]-> [2 | ]-> [NULL node]
[2 | ]-> [0 | ]-> [1 | ]-> [NULL node]

3个节点的图形,顶点编号为0-2,右边?

所以这是我正在实施的代码:

struct node {
    int vertex;
    node *next;
};

node *headnodes;
bool *Visited;
bool cycles = false;// determine if a graph has cycles.

class Graph {

    private: 
        int n; // number of vertices
        int e; // number of edges
        //node *headnodes;

    public:  
        Graph(int nodes) // construtor
        {
            n = nodes;
            headnodes = new node[n]; // headnodes is an array of nodes.
            for (int i = 0; i < n; i++)
            {
                headnodes[i].vertex = i;
                headnodes[i].next = 0; //points null
            }
        }

        //This function is based off lecture notes (Lecture 13)
        //node graph
        int Graph::create()
        {
            //iterate through the head nodes
            for (int i = 0; i < n; i++) {
                cout << "Initializing " << i << "-th node.\n";
                if (i == 0){
                    //headnode 0 points to its adjacent nodes 1, and 2
                    headnodes[n].next = new node; //initialize new node
                    node link = headnodes[n]; //assign to new variable
                    link.vertex = 1;
                    link.next->vertex = 2;
                    link.next->next = 0;
//This works
                    cout << "vertex of first node: " << headnodes[n].next->vertex; 
                } else if (i == 1){
                    headnodes[n].next = new node; //initialize new node
                    node link = headnodes[n];
                    link.vertex = 0; //the first node
                    link.next->vertex = 3; //the second node
                    //the 3rd node
                    /*link.next = new node;
                    node *link2 = link.next;
                    link.next->next->vertex = 4;
                    link.next->next->next = 0;*/
                } else if (i == 2){
                    headnodes[n].next = new node; //initialize new node
                    node link = headnodes[n];
                    link.vertex = 0;
                    link.next->vertex = 3;
                    link.next->next = 0;
                }
            }
//This doesn't?
            cout << "Checking vertex";
            cout << "First node's link vert: " << headnodes[0].next->vertex; //ERROR, Access Violation!
            return 0;
        }
};

我认为,因为headnodes变量是全局的,所以它会很好,但它会导致RunTime错误(访问冲突),显然它指向一个空节点(但它是全局的,所以它是全局的WTH)?我没有弄错。

有人能指出我正确的方向吗?我觉得我很接近。

1 个答案:

答案 0 :(得分:1)

你的问题很简单。在create函数中,您尝试迭代邻接列表,但是您不断索引n-th headnode,您可能知道它超出了数组的范围。

您将{3}作为nodes传递给n并在循环中继续将其编入headnodes[n]。您可以在每次cout << n << endl;访问之前添加headnodes来验证这一点;你每次都会看到3

您可能希望根据i将它们编入索引,因为它将是迭代索引。