1 package Graph; 2 /**使用邻接表 生成图*/ 3 public class Graph { 4 5 public int Vertex; 6 public int EdgeNum; 7 VNode[] graph; 8 public Graph(int V[],int E, int [][]vertex,int [] weight) 9 { 10 this.Vertex=V.length; 11 this.EdgeNum=E; 12 graph=new VNode[V.length]; 13 CreateGraph (graph ,vertex,weight,V); 14 15 } 16 public void PrintGraph(VNode[]graph) 17 { 18 for(int i=0;i<graph.length;i++) 19 { 20 System.out.print(graph[i].verternum+"-->"); 21 PrintEdge(graph[i].firstedge); 22 System.out.println(); 23 } 24 } 25 public void PrintEdge(EdgeNode p) 26 { 27 while(p!=null) 28 { 29 System.out.print("("+p.adjvex+","+p.weight+")"+" "); 30 p=p.nextedge; 31 } 32 33 } 34 public void CreateGraph(VNode []graph,int [][]vertex,int []weight,int Vnum[]) 35 { 36 for(int i=0;i<graph.length;i++) 37 { // 初始化邻接链表的值, 38 graph[i]=new VNode(Vnum[i]); 39 40 } 41 42 for(int i=0;i<weight.length;i++) 43 { 44 45 for(int j=0;j<graph.length;j++) 46 { 47 if(vertex[i][0]==graph[j].verternum) 48 { 49 addEdge(graph[j],vertex[i][1],weight[i]); 50 } 51 } 52 } 53 54 } 55 56 public void addEdge(VNode vertex ,int adj,int weight) 57 { 58 /** 59 * 功能: 在邻接表后面增加边*/ 60 if(vertex.firstedge==null) 61 { 62 vertex.firstedge=new EdgeNode(adj,weight); 63 } 64 else 65 { 66 EdgeNode phead=vertex.firstedge; 67 while(phead.nextedge!=null) 68 { 69 phead=phead.nextedge; 70 } 71 phead.nextedge=new EdgeNode(adj,weight); 72 } 73 74 } 75 public static void main(String [] args) 76 { 77 int [][]array={{1,2},{1,3},{1,4},{2,4},{2,3},{3,4}}; 78 int weight[]={1,2,3,4,5,6}; 79 int []vNum={1,2,3,4}; 80 Graph graph=new Graph(vNum,weight.length,array,weight); 81 graph.PrintGraph(graph.graph); 82 } 83 } 84 class VNode 85 { 86 /** 87 * 顶点的信息*/ 88 int verternum; 89 EdgeNode firstedge=null; 90 public VNode(int v) 91 { 92 this.verternum=v; 93 } 94 95 } 96 class EdgeNode 97 { 98 /** 99 *邻接表定义 */ 100 int adjvex;//顶点的编号 101 int weight; 102 EdgeNode nextedge=null; 103 // 无权图 104 public EdgeNode(int adj) 105 { 106 this.adjvex=adj; 107 this.weight=1; 108 109 } 110 //有权图 111 public EdgeNode(int adj,int wt) 112 { 113 this.adjvex=adj; 114 this.weight=wt; 115 116 } 117 }
结果显示 1-->(2,1) (3,2) (4,3) 2-->(4,4) (3,5) 3-->(4,6) 4-->