帮我写一个有向图数据结构,用Java 写
时间: 2023-06-17 21:07:34 浏览: 149
当然可以帮您编写有向图数据结构,以下是示例代码:
```java
import java.util.*;
public class DirectedGraph {
private Map<Integer, List<Integer>> adjacencyList;
public DirectedGraph() {
this.adjacencyList = new HashMap<>();
}
public void addVertex(int vertex) {
adjacencyList.put(vertex, new LinkedList<>());
}
public void addEdge(int from, int to) {
if (!adjacencyList.containsKey(from))
addVertex(from);
if (!adjacencyList.containsKey(to))
addVertex(to);
adjacencyList.get(from).add(to);
}
public List<Integer> getAdjacentVertices(int vertex) {
return adjacencyList.get(vertex);
}
public int getVertexCount() {
return adjacencyList.keySet().size();
}
public List<Integer> getVertices() {
return new ArrayList<>(adjacencyList.keySet());
}
}
```
该有向图数据结构使用邻接表实现,可以通过调用 `addVertex` 方法添加顶点,通过 `addEdge` 方法添加边,通过 `getAdjacentVertices` 方法获取某个顶点的相邻顶点列表,通过 `getVertexCount` 方法获取顶点数量,通过 `getVertices` 方法获取所有顶点列表。
阅读全文