import java.util.Scanner;
public class ALGraph<T> {//用邻接表存储图的定义
public class ArcNode {//边节点的定义
int adjVex;//存放邻接点的序号
ArcNode nextArc;//指向vi下一个邻接点的边节点
int weight;//权值
public ArcNode() {
adjVex = 0;
weight = 0;
nextArc = null;
}
}
public class VNode<T> {//顶点的定义
T data;//储存顶点的数据信息
ArcNode firstArc;//指向顶点vi的第一个邻接点的边节点
public VNode() {
data = null;
firstArc = null;
}
}
protected final int MAXSIZE = 10;
protected VNode[] adjList;//由各顶点组成的数组
int n, e;//图的顶点数和弧数
public ALGraph() {
adjList = new VNode[MAXSIZE];
}
public void CreateLink() {//创建无向图的邻接表
int i, j, k;
T v1, v2;
ArcNode s;
String str;
Scanner sc = new Scanner(System.in);
System.out.println("请输入图的顶点以及边数:");
System.out.print("顶点数 n=");
n = sc.nextInt();
System.out.print("边 数 e=");
e = sc.nextInt();
System.out.print("请输入图的顶点信息:");
str = sc.next();
for (i = 0; i < n; i++) {
adjList[i] = new VNode<T>();
adjList[i].data = str.charAt(i);//构造顶点信息
adjList[i].firstArc = null;
}
System.out.println("请输入图的边的信息:");
for (k = 0; k < e; k++) {
System.out.print("请输入第" + (k + 1) + "条边的两个顶点:");
str = sc.next();//输入一条边的两个顶点
v1 = (T) (Object) str.charAt(0);
v2 = (T) (Object) str.charAt(1);
//确定两个顶点在图G中的位置
i = LocateVex(v1);
j = LocateVex(v2);
if (i >= 0 && j >= 0) {
s = new ArcNode();
s.adjVex = j;
s.nextArc = adjList[i].firstArc;
adjList[i].firstArc = s;
s = new ArcNode();
s.adjVex = i;
s.nextArc = adjList[j].firstArc;
adjList[j].firstArc = s;
}
}
}
public int LocateVex(T v) {//查找顶点v,找到后返回其在顶点数组中的索引号
int i;
for (i = 0; i < n; i++) {
if (adjList[i].data == v) {
return i;
}
}
return -1;
}
public void DisplayAdjList() {//显示图的邻接表表示
int i;
ArcNode p;
System.out.println("图的邻接矩阵表示:");
for (i = 0; i < n; i++) {
System.out.print("\n " + adjList[i].data);
p = adjList[i].firstArc;
while (p != null) {
System.out.print("-->" + p.adjVex);
p = p.nextArc;
}
}
}
public static void main(String[] args) {
ALGraph<Character> G = new ALGraph<Character>();
G.CreateLink();
G.DisplayAdjList();
}
}