尝试在C++中创建具有邻接列表的图形
Trying to create a graph with adjacency list in C++
我正在尝试在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 个之间循环。
相关文章:
- 从流到邻接列表的向量读取图形
- 替代在python中制作邻接列表与图形问题的字典?(如 C++ 中的 vector<vector<int&g
- 通过相邻顶点列表添加和减去图形中的边
- 如何显示图形邻接列表的元素?
- 如何从图形的邻接列表表示中随机选择边缘
- BFS 用于使用链接列表、C++ 的图形
- 自定义图形列表视图项目不更改文本颜色
- 包含相邻顶点列表的自定义顶点类型[图形]:不完整类型错误
- 使用邻接列表将顶点添加到图形
- 在 c++ stl 中通过邻接列表正确实现图形
- 图形的邻接列表表示形式不正确
- 尝试在C++中创建具有邻接列表的图形
- 邻接列表,用于创建图形和广度优先搜索 (BFS) 和 Fepth First Search (DFS)
- 视觉 我正在使用C++用于一些基本图形。我想知道如何读取顶点、索引和面以及如何在数组列表中使用面?
- 图形、顶点、STL 列表:为什么列表是空的
- C++:图形 ADT 应该有一个顶点列表和一个边列表,或者只是带有指向其他顶点的指针的顶点
- 邻接列表的图形声明
- 相邻列表自引用到图形对象
- c++中向量与列表的图形表示
- 使用 unordered_map 实现图形表示的邻接列表