【发布时间】:2021-03-24 14:59:01
【问题描述】:
我有一个存储链表数组的 Graph 类。 我想在链表的头部插入并将新项目的“下一个”设置为前一个头部。 但是,当我将新头的“下一个”设置为前一个头时,它最终会将新头设置为自己的下一个,从而导致无限循环,因为下一个也指向自身。 特别是 insert() 中的这一行
EdgeNode node = EdgeNode(y, weight, edges[x].isEmpty() ? nullptr : &edges[x]);
node 对象对它自己和下一个对象都有正确的和预期的值。 但是,一旦我将 node 分配给数组,
edges[x] = node;//This causes "next" to contain its own reference., causing circular dependency
它变坏了,并将 edges[x].getnext() 也分配为 edges[x] 导致循环引用。 我什至有自己的重载赋值运算符,但它没有帮助。 我认为它归结为简单的指针操作。除了如何修复它,请解释为什么它不起作用。不想使用智能指针或将链表对象数组更改为指针数组。
最后是 Graph 类和 main()
#include <iostream>
const int MAX_VERTICES = 1000;
class EdgeNode {
int y{ -1 };
int weight{ 1 };
EdgeNode* next{ nullptr };
public:
EdgeNode() : y(-1), weight(1), next(nullptr) {}
EdgeNode(int _y, int _weight, EdgeNode* _next) : y{ _y }, weight{ _weight }, next(_next) {}
EdgeNode& operator=(const EdgeNode& other) {
this->next = other.getNext();
this->y = other.getY();
this->weight = other.getWeight();
return *this;
}
int getY() const { return y; } ;
int getWeight() const { return weight; };
EdgeNode* getNext() const { return next; };
bool const isEmpty() { return y == -1; }
};
class Graph {
EdgeNode edges[MAX_VERTICES];
public:
Graph() {};
void insertEdge(int x, int y, int weight, bool directed) {
EdgeNode node = EdgeNode(y, weight, edges[x].isEmpty() ? nullptr : &edges[x]);
edges[x] = node;//This causes "next" to contain its own reference., causing circular dependency
if (directed) {
insertEdge(y, x, weight, false);
}
}
};
int main()
{
std::cout << "Hello World!\n";
Graph graph;
graph.insertEdge(1, 11);
graph.insertEdge(1, 111);
}
【问题讨论】:
标签: c++ pointers graph linked-list