(学习java)邻接表 图的简单创建

来源:互联网 发布:ssh端口号 编辑:程序博客网 时间:2024/06/05 05:56
//定义顶点结点public class Vertex {private char vertex;private Side side;public Vertex() {super();this.vertex = '\0';this.side = null;// TODO Auto-generated constructor stub}public Vertex(char vertex, Side first) {super();this.vertex = vertex;this.side = first;}public char getVertex() {return vertex;}public void setVertex(char vertex) {this.vertex = vertex;}public Side getSide() {return side;}public void setSide(Side first) {this.side = first;}}

//边结点public class Side {private char name;//定义权重private int weight;//指向后继结点private Side next;public Side() {super();}public Side(char name, int weight) {super();this.name = name;this.weight = weight;this.next = null;}public int getWeight() {return weight;}public void setWeight(int weight) {this.weight = weight;}public Side getNext() {return next;}public void setNext(Side next) {this.next = next;}}

import java.util.Scanner;//邻接表public class MyGraph {// 一维数组储存所有顶点private Vertex[] graph;// 边的数量int numSide;// 顶点的数量int numVertex;public MyGraph() {super();// TODO Auto-generated constructor stub}public void createGraph() {// 输入边和顶点的数量Scanner sc = new Scanner(System.in);Scanner sc2 = new Scanner(System.in);System.out.println("请输入边的数量");numSide = sc.nextInt();System.out.println("请输入顶点的数量");numVertex = sc.nextInt();// 输入顶点getVertex();// 输入边for (int i = 0; i < graph.length; i++) {getfirst(graph, i);}}// 定义边private void getfirst(Vertex[] graph, int n) {Scanner sc = new Scanner(System.in);Scanner sc2 = new Scanner(System.in);System.out.println("请输入顶点" + graph[n].getVertex() + "的邻结点的数量 :");int num = sc.nextInt();System.out.println("请输入邻结点");String str = sc2.nextLine();// 将第一个结点和他的所有邻结点放入字符数组中char[] newStr = (graph[n].getVertex() + str.replaceAll("[^1-9a-zA-Z]*","").substring(0, num)).toCharArray();// 定义graph的头结点 值为nullSide pre = new Side();graph[n].setSide(pre);// 邻结点数量为0if (num == 0) {} else {for (int j = 1; j < newStr.length; j++) {System.out.println("请输入" + newStr[0] + "到" + newStr[j] + "的权重");int weight = sc.nextInt();Side side = new Side(newStr[j], weight);pre.setNext(side);pre = side;}}}// 获取顶点public void getVertex() {Scanner sc = new Scanner(System.in);this.graph = new Vertex[numVertex];System.out.println("请输入顶点:");String str = sc.nextLine();char[] newStr = str.replaceAll("[^1-9a-zA-Z]*", "").substring(0, numSide).toCharArray();for (int i = 0; i < newStr.length; i++) {// 创建graph[]中每个vertex对象graph[i] = new Vertex(newStr[i], null);}}}
测试类
public class Test02 {public static void main(String[] args) {MyGraph m = new MyGraph();m.createGraph();System.out.println("hello");}}



原创粉丝点击