尝试在C++中创建具有邻接列表的图形

Trying to create a graph with adjacency list in C++

本文关键字:列表 图形 C++ 创建      更新时间:2023-10-16

我正在尝试在C++中创建具有邻接列表结构的图形。当我执行代码时,它会进入无限循环。在addEdge函数的某个地方,我犯了一个错误,我似乎无法发现。任何帮助将不胜感激。谢谢。

 class Graph
    {
        struct AdjListNode
        {
            int dest;
            AdjListNode* next;
        };
        AdjListNode* array;
        int V;
        bool directed;
    public:
        Graph (int V, bool directed);
        ~Graph();
        void addEdge(int src, int dest);
        void printGraph();
    };
#include <iostream>
#include "Graph.h"
using namespace std;
Graph::Graph(int nVertices,bool directed)
{
    this->V = nVertices;
    this->directed = directed;
    // Create an array of adjacency lists.  Size of array will be V
    this->array = new AdjListNode[V];
    for (int i = 0; i < V; i++)
    {
        this->array[i].next = NULL;
    }
}
Graph::~Graph()
{
    delete[] array;
}
void Graph::addEdge(int src, int dest)
{
    AdjListNode* newNode = new AdjListNode;
    newNode->dest = dest;
    newNode->next = &(this->array[src]);
    this->array[src].next = newNode;
    cout << "Deneme = " << this->array[src].dest << endl;
    if (this->directed == false)
    {
        newNode = new AdjListNode;
        newNode->dest = src;
        newNode->next = &(this->array[dest]);
        this->array[dest].next = newNode;
    }
}
void Graph::printGraph()
{
    for(int i=0; i < this->V; i++)
    {
        AdjListNode* pCrawl = &(this->array[i]);
        cout << "Adjacency list of vertex " << i;
        while (pCrawl)
        {
            cout << "-> " << pCrawl->dest;  
            pCrawl = pCrawl->next;
        }
        cout << endl;
    }
}
int main()
{
    // create the graph given in above fugure
    int V = 5;
    Graph* g = new Graph(V,false);
    g->addEdge(0, 1);
    g->addEdge(0, 4);
    g->addEdge(1, 2);
    g->addEdge(1, 3);
    g->addEdge(1, 4);
    g->addEdge(2, 3);
    g->addEdge(3, 4);
    g->printGraph();
    return 0;
}

翻译成伪代码语言,你的addEdge看起来像这样:

Create a new empty node called A
Set destiation as given by input.
Assign the next entry of A the reference of src (let's call it B)
Assign the next entry of B as beeing A.
所以现在 A 在 B 旁边

,B 在 A 旁边!你的 pCrawl 只会在这 2 个之间循环。