邻接表实现

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);