链表实现的一个图

Linked List implementation of a Graph

本文关键字:一个 实现 链表      更新时间:2023-10-16

我对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变量是全局的,那就好了,但它会导致运行时错误(访问违反),显然它指向一个空节点(但它是全局的)?我不明白哪里不对。

谁能给我指个正确的方向?

你的问题很直接。在你的create函数中,你尝试迭代邻接表,但是你不断地索引n-th headnode,你可能知道它在数组的边界之外。

您将3传递为nodes并将其分配给n,并在循环中继续将其索引为headnodes[n]。您可以通过在每次访问headnodes之前添加cout << n << endl;来验证这一点;你每次都会看到3

您可能希望根据i对它们进行索引,因为这将是迭代索引。