邻接表实现
Adjacency list implementation
本文关键字:实现 更新时间:2023-10-16
我正在尝试实现一个简单的邻接表。我知道数组的索引是该点顶点的键。
例如:如果我有如下格式的边:(start, finish, cost)(1、2、4)(2、3、5)(1、3、27)(3、4、8)
我将得到一个数组
[0] -> null
[1] -> 2|4 -> 3|27 -> null
[2] -> 3|5 -> null
[3] -> 4|8 -> null
一个问题是,保存边的容器有指针,但插入其中的元素(边)没有。我迷路了。
正在编辑这篇文章,因为我不知道如何在评论中放置代码。
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个属性(source, destination, cost)现在这只是不停地给链表添加边而已。我如何按来源分开列表?
邻接表不一定是链表。即使是,也不要自己实现(侵入式)链表,使用现有的实现。
但是现在我们开始;只要有一个(节点,成本)对的向量:
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);
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的