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

时间:2015-01-12 11:44:27

标签: c++ graph

我正在尝试在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;
}

1 个答案:

答案 0 :(得分:1)

转换为伪代码语言,你的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将在这两个之间循环。