在Java中,使用邻接表存储图的数据结构通常涉及到两个类:一个表示节点(或顶点),另一个表示边
import java.util.ArrayList;
import java.util.List;
public class Node {
private int value;
private List<Node> neighbors;
public Node(int value) {
this.value = value;
this.neighbors = new ArrayList<>();
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public List<Node> getNeighbors() {
return neighbors;
}
public void setNeighbors(List<Node> neighbors) {
this.neighbors = neighbors;
}
public void addNeighbor(Node neighbor) {
this.neighbors.add(neighbor);
}
}
import java.util.ArrayList;
import java.util.List;
public class Graph {
private List<Node> nodes;
public Graph() {
this.nodes = new ArrayList<>();
}
public List<Node> getNodes() {
return nodes;
}
public void setNodes(List<Node> nodes) {
this.nodes = nodes;
}
public void addNode(Node node) {
this.nodes.add(node);
}
public void addEdge(Node from, Node to) {
from.addNeighbor(to);
to.addNeighbor(from); // 如果是无向图
}
}
public class Main {
public static void main(String[] args) {
Graph graph = new Graph();
Node nodeA = new Node(1);
Node nodeB = new Node(2);
Node nodeC = new Node(3);
graph.addNode(nodeA);
graph.addNode(nodeB);
graph.addNode(nodeC);
graph.addEdge(nodeA, nodeB);
graph.addEdge(nodeB, nodeC);
graph.addEdge(nodeC, nodeA);
// 输出邻接表
for (Node node : graph.getNodes()) {
System.out.print("Node " + node.getValue() + " is connected to: ");
for (Node neighbor : node.getNeighbors()) {
System.out.print(neighbor.getValue() + " ");
}
System.out.println();
}
}
}
这将创建一个包含3个节点的无向图,并输出它们的邻接表。你可以根据需要修改这些类以适应你的特定需求。