0

我正在尝试实现一个简单的邻接列表。我知道数组的索引是此时顶点的键。

例如:如果我有格式的边缘:(开始,结束,成本)(1,2,4)(2,3,5)(1,3,27)(3,4,8)

我会有一个数组

[0] -> 空

[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 个属性(源、目标、成本) 现在它什么也不做,只是在链表中不断添加边缘。如何按来源分隔列表?

4

1 回答 1

2

邻接表不一定是链表。即使是这样,也不要自己实现(侵入式)链表,使用现有的实现。

但是,我们走了;只有一个(节点,成本)对的向量:

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);
于 2013-03-24T17:59:06.250 回答