在这个实例中,我们将用Java实现图形数据结构。
class Graph { //内部类 class Edge { int src, dest; } //顶点和边的数量 int vertices, edges; //存储所有边的数组 Edge[] edge; Graph(int vertices, int edges) { this.vertices = vertices; this.edges = edges; //初始化边数组 edge = new Edge[edges]; for(int i = 0; i < edges; i++) { //边数组的每一个元素 //是Edge类型的对象 edge[i] = new Edge(); } } public static void main(String[] args) { //创建一个Graph类的对象 int noVertices = 5; int noEdges = 8; Graph g = new Graph(noVertices, noEdges); //创建图 g.edge[0].src = 1; // edge 1---2 g.edge[0].dest = 2; g.edge[1].src = 1; // edge 1---3 g.edge[1].dest = 3; g.edge[2].src = 1; // edge 1---4 g.edge[2].dest = 4; g.edge[3].src = 2; // edge 2---4 g.edge[3].dest = 4; g.edge[4].src = 2; // edge 2---5 g.edge[4].dest = 5; g.edge[5].src = 3; // edge 3---4 g.edge[5].dest = 4; g.edge[6].src = 3; // edge 3---5 g.edge[6].dest = 5; g.edge[7].src = 4; // edge 4---5 g.edge[7].dest = 5; //打印图表 for(int i = 0; i < noEdges; i++) { System.out.println(g.edge[i].src + " - " + g.edge[i].dest); } } }
输出结果
1 - 2 1 - 3 1 - 4 2 - 4 2 - 5 3 - 4 3 - 5 4 - 5
在上面的示例中,我们已经用Java实现了图形数据结构。