我正在尝试实现一个简单的邻接表。我知道数组的索引是顶点的关键字。
例如:如果我有以下格式的边:(开始,完成,成本) (1,2,4) (2,3,5) (1,3,27) (3,4,8)
我将有一个数组,它将是
->为空
1 -> 2|4 -> 3|27 ->空
2 -> 3|5 ->空
3个-> 4|8个->空
一个问题是,持有边的容器有指针,但插入其中的元素(边)没有。我迷路了。
编辑这篇文章是因为我不知道如何在评论中添加代码。
struct Node{
Edge *head;
Node *next;
}
Node *root;
void adjacencyList::insert(const Edge &edge)
{
if(root == NULL)
{
root = new Node;
root->head = edge;
}
else
{
while(root != NULL)
{
root = root->next;
if(root == NULL);
{
root = new Node;
root->head = edge;
root = root ->next;
}
}
}
}边缘对象有3个属性(源、目标、成本),现在除了在链表中不断添加边缘之外,什么也不做。如何按来源分隔列表?
发布于 2013-03-25 01:59:06
邻接表不必是链表。即使是这样,也不要自己实现(介入式)链表,使用现有的实现。
但现在我们开始了;只有一个(节点,成本)对的向量:
typedef std::pair<int, int> weighted_node_t;
typedef std::vector<std::vector<weighted_node_t>> graph_t;然后,您可以按如下方式表示图形(使用C++11初始化语法):
graph_t graph{
{},
{{2, 4}, {3, 27}},
{{3, 5}},
{{4, 8}}
};现在让我们假设您想要遍历图(深度优先搜索),您将执行以下操作(同样,使用C++11语法,因为它更简洁):
void dfs(graph_t const& graph, std::vector<bool>& visited, int node) {
visited[node] = true;
for (auto const& neighbor : graph[node])
if (not visited[neighbor])
dfs(graph, visited, neighbor.first);
}然后这样叫它:
std::vector<bool> visited(graph.size());
dfs(graph, visited, 1);https://stackoverflow.com/questions/15601570
复制相似问题