-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.js
51 lines (44 loc) · 1.24 KB
/
Graph.js
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
class Graph {
constructor() {
this.size = 0;
this.firstVertex = null;
}
insertVertex(key) {
const newVertex = new Vertex(key);
let last = this.firstVertex;
if (last === null) {
this.firstVertex = newVertex;
}
else {
while (last.nextVertex !== null) {
last = last.nextVertex;
}
last.nextVertex = newVertex;
}
this.size++;
}
insertEdge(data, tail, head) {
let tailVertex = this.firstVertex;
let headVertex = this.firstVertex;
while (tailVertex && tailVertex.key !== tail) {
tailVertex = tailVertex.nextVertex;
}
while (headVertex && headVertex.key !== head) {
headVertex = headVertex.nextVertex;
}
if (tailVertex === null || headVertex === null) {
return false;
}
const newEdge = new Edge(data, headVertex);
let lastEdge = tail.edge;
if (lastEdge !== null) {
while (lastEdge.nextEdge !== null) {
lastEdge = lastEdge.nextEdge;
}
lastEdge.nextEdge = newEdge;
}
else {
tail.edge = newEdge;
}
}
}