在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個節點的無向圖,并輸出它們的鄰接表。你可以根據需要修改這些類以適應你的特定需求。