-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacencyList.java
More file actions
92 lines (78 loc) · 2.42 KB
/
Copy pathAdjacencyList.java
File metadata and controls
92 lines (78 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Week9.Tutorial;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* @author szeyu
*/
class EdgeNodes<E>{
protected Vertex<E> vertice;
protected EdgeNodes nextEdgeNode;
public EdgeNodes(Vertex vertice){
this.vertice = vertice;
this.nextEdgeNode = null;
}
}
class Vertex<E> {
private E vertexInfo;
private EdgeNodes firstEdgeNodes;
public Vertex(E vertexInfo){
this.vertexInfo = vertexInfo;
firstEdgeNodes = null;
}
public void linkTo(Vertex toVertex){
if(firstEdgeNodes == null){
firstEdgeNodes = new EdgeNodes(toVertex);
return;
}
EdgeNodes current = firstEdgeNodes;
while(current.nextEdgeNode != null){
current = current.nextEdgeNode;
}
current.nextEdgeNode = new EdgeNodes(toVertex);
}
public E getVertexInfo() {
return vertexInfo;
}
@Override
public String toString(){
StringBuilder out = new StringBuilder();
out.append(vertexInfo);
EdgeNodes current = firstEdgeNodes;
while (current != null){
out.append(" -> ");
out.append(current.vertice.getVertexInfo());
current = current.nextEdgeNode;
}
return out.toString();
}
}
public class AdjacencyList<E> {
private ArrayList<Vertex> vertices;
private HashMap<E, Integer> verticeMapIndex;
public AdjacencyList(){
vertices = new ArrayList<>();
verticeMapIndex = new HashMap<>();
}
public void addVetice(E verticeInfo){
Vertex<E> newVertice = new Vertex<>(verticeInfo);
verticeMapIndex.put(verticeInfo, vertices.size());
vertices.add(newVertice);
}
public void addLink(E fromVertice, E toVertice){
if(!verticeMapIndex.containsKey(fromVertice) || !verticeMapIndex.containsKey(toVertice)){
System.out.println("Fail to add link");
return;
}
vertices.get(verticeMapIndex.get(fromVertice)).linkTo(vertices.get(verticeMapIndex.get(toVertice)));
}
public void print(){
for (Vertex vertice : vertices) {
System.out.println(vertice);
}
}
}