【发布时间】:2014-12-17 15:57:38
【问题描述】:
我进行了搜索,但找不到特定于我的案例的任何内容。
我想在 C++ 中仅使用链表实现一个图形。我的结构如下:
class Vertex
{
public:
Vertex(std::string name = "none");
private:
std::string name;
Edge *edges;
Vertex *next;
Runnable *runnables;
};
class Edge
{
public:
Edge();
private:
Vertex *connectsTo;
Edge *next;
};
class TaskGraph{
public:
TaskGraph();
private:
Vertex *head;
};
我有一种方法可以向图中添加顶点 void addVertex(TaskGraph* taskGraph, const std::string&);
这种方法效果很好,因为我可以打印出图中的所有顶点。另一方面,为了添加有向边,我做了这样的事情:
void MyGraph::addEdge(TaskGraph* taskGraph, const string& src, const string& dest){
//get to the source vertex: this is ok
//get to the destination vertex: this is also ok
//add edge : the problem is here // s is source vertex while d is destination vertex.
Edge *e = new Edge;
e->connectsTo = d;
if(s->edges == 0){
s->edges = e;
}else{
s->edges->next = e;
}
}
添加 5 条边 后,实际上只添加了 两条(即第一条边和列表边,正在替换其他边)。我发现这是因为这条线:“s->edges->next = e;” 但无法弄清楚如何正确实现它。请帮忙!!!
谢谢
【问题讨论】:
-
变量
s是什么? -
看起来您正在使用
Vertex类的Edge* edges成员作为指向单个Edge对象的指针。如果您想支持一个顶点可以与多个其他顶点相邻的图形,这似乎不起作用。 -
s 是源顶点。 @rchang 我明白你的意思。我应该做些什么。谢谢
-
你在做 s->edges->next = e;。但是如果s->edges->next的前一个值不为null(>列表中有2个元素)呢?
标签: c++ linked-list