链表实现的一个图
Linked List implementation of a Graph
我对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
对它们进行索引,因为这将是迭代索引。
相关文章:
- 实现一个在集合上迭代的模板函数
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如何为位集找到/实现一个好的哈希函数
- C++哈希表中,两个相同的实现,但一个给出错误
- 如何将这两个函数组合成一个实现?
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 为什么这个快速排序实现给出了一个奇怪的输出
- C++:实现一个全局常量,其值由用户给出
- C++:实现一个接收lambda作为输入的高阶函数
- std::sort 一个实现了移动构造函数的类
- GMock - 用另一个实现模拟抽象类
- 有没有办法(C++)创建一个实现某些功能的模板类?
- 创建一个实现选项卡并可用作 QMainWindow 中的"central widget"的类
- 说出一个实现STL兼容序列容器的好指南)
- 一个C++实现的隐马尔可夫模型林安装错误
- 一个实现是否允许在同一地址放置两个相同的函数定义