现在在看图。说是邻接表是用来表示图的标准方法,我照着自己的理解写了一个用来表示一个有向图,只是用来表示图而已,没有做任何其它的工作。也不知道规范不规范。
- /**
- * 图的顶点
- */
- package com.mygraph;
- public class Vertex {
- private Object num; //顶点的名称
- public Link link; //链表,用来存放从该顶点出发的边的信息
- public Vertex(Object num){
- this.num=num;
- link=new Link();
- }
- }
- /**
- * 链表的节点
- */
- package com.mygraph;
- public class Node {
- private Object verNum; //顶点的名称
- private int weight; //到顶点verNum的边的权重
- public Node next;
- public Node(Object verNum,int weight){
- this.verNum=verNum;
- this.weight=weight;
- next=null;
- }
- public Object getVerNum() {
- return verNum;
- }
- public int getWeight() {
- return weight;
- }
- }
- /**
- * 链表,存放边的信息
- */
- package com.mygraph;
- public class Link {
- Node current;
- Node first;
- public Link(){
- current=null;
- first=null;
- }
- //增加节点
- public void add(Object num,int weight){
- Node tempNode=new Node(num, weight);
- if(current==null){
- current=tempNode;
- first=tempNode;
- }
- else {
- current.next=tempNode;
- current=tempNode;
- }
- }
- //遍历该链表 即遍历从某顶点出发的所有边
- public void trackLink(int from){
- Node cursor=first;
- if(cursor==null)
- System.out.println("从顶点\""+from+"\"出发没有边!");
- while(cursor!=null)
- {
- System.out.println("边:<"+from+","+cursor.getVerNum()+"> 权="+cursor.getWeight());
- cursor=cursor.next;
- }
- }
- }
- /**
- * 图
- */
- package com.mygraph;
- public class Graph {
- //图的顶点
- Vertex[] vertexs;
- //构建图,nums图中顶点的个数
- public Graph(int nums){
- vertexs=new Vertex[nums+1];
- for(int i=1;i<=nums;i++)
- vertexs[i]=new Vertex(i);
- }
- //增加边
- public void addEdge(int from,int to,int weight){
- vertexs[from].link.add(to, weight);
- }
- //查找从某顶点出发的所有边
- public void queryEdges(int VetexNum){
- vertexs[VetexNum].link.trackLink(VetexNum);
- }
- public static void main(String[] args){
- Graph graph=new Graph(7);
- graph.addEdge(1, 2, 3);
- graph.addEdge(1, 3, 5);
- graph.addEdge(1, 4, 6);
- graph.addEdge(2, 4, 6);
- graph.addEdge(2, 5, 3);
- graph.addEdge(3, 6, 1);
- graph.addEdge(4, 3, 4);
- graph.addEdge(4, 6, 6);
- graph.addEdge(4, 7, 3);
- graph.addEdge(5, 4, 5);
- graph.addEdge(5, 7, 7);
- graph.addEdge(7, 6, 4);
- for(int i=1;i<=7;i++)
- {
- System.out.println("顶点"+i);
- graph.queryEdges(i);
- System.out.println("**********************");
- }
- }
- }
代码里试图表示的是下面这个有向图:
运行结果:
顶点1
边:<1,2> 权=3
边:<1,3> 权=5
边:<1,4> 权=6
**********************
顶点2
边:<2,4> 权=6
边:<2,5> 权=3
**********************
顶点3
边:<3,6> 权=1
**********************
顶点4
边:<4,3> 权=4
边:<4,6> 权=6
边:<4,7> 权=3
**********************
顶点5
边:<5,4> 权=5
边:<5,7> 权=7
**********************
顶点6
从顶点"6"出发没有边!
**********************
顶点7
边:<7,6> 权=4
**********************
应该算是把这个有向图表示出来了吧。。。