邻接表

也是以前自己的笔记,直接从为知笔记中复制过来的。
那时候自己脑子抽了,忘了可以直接从百度中搜索Java语言的图的相关知识,便仿照C语言版数据结构的教科书图那章的知识点花了一下午的时间写出来的。
额。。好像还是没有多少注释。


package com.ct.graph;
import java.util.Scanner;
//边
class Edge{
public int index; //边所连接节点
public Edge next; //指向下一个节点
}
//顶点
class VexNode{
public char data; //顶点中数据
Edge firstedge; //数组指向的下一个节点
}
//邻接表
class Graph{

VexNode adjVex[] = new VexNode[100]; //邻接表中的数组
public Graph(){
for(int i=0; i<100; i++){
adjVex[i] = new VexNode();
}
}

public int vexnum, arcnum; //顶点数目,边的数目
}
public class Main {

//创建邻接表
static Graph create(){
Graph G = new Graph();
Scanner sc = new Scanner(System.in);

System.out.println("输入顶点和边的数目");
G.vexnum = sc.nextInt();
G.arcnum = sc.nextInt();

System.out.println("输入顶点数据:");
for(int i=0; i<G.vexnum; i++){
System.out.printf("输入第%d个顶点的数据: ",i+1);
G.adjVex[i].data = sc.next().charAt(0);
G.adjVex[i].firstedge = null;
}

System.out.println("输入边的信息:");
for(int i=0; i<G.arcnum; i++){
System.out.printf("输入第%d条边连接的顶底(以空格隔开): ",i+1);
char v1 = sc.next().charAt(0);
char v2 = sc.next().charAt(0);

int index1 = locate(v1,G);
int index2 = locate(v2,G);

Edge e;

e = new Edge();
e.index = index2;
e.next = G.adjVex[index1].firstedge;
G.adjVex[index1].firstedge = e;

e = new Edge();
e.index = index1;
e.next = G.adjVex[index2].firstedge;
G.adjVex[index2].firstedge = e;
}
return G;
}

//返回数据位置
static int locate(char data, Graph G){
int result = -1;
for(int i=0; i<G.vexnum; i++){
if(data == G.adjVex[i].data){
result = i;
break;
}
}

return result;
}

//输出邻接表的内容
static void print(Graph G){
for(int i=0; i<G.vexnum; i++){
System.out.print(G.adjVex[i].data);
Edge e = G.adjVex[i].firstedge;
while(e != null){
System.out.print(G.adjVex[e.index].data);
e = e.next;
}
System.out.println();
}
}

public static void main(String[] args) {
Graph G = create();
print(G);

}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值