<script>
class AdjNode {
constructor(data) {
this
.vertex = data;
this
.next =
null
;
}
}
class AdjList {
constructor(vertices) {
this
.v = vertices;
this
.graph =
new
Array(
this
.v).fill(
null
);
}
addEdge(source, destination) {
const node =
new
AdjNode(destination);
node.next =
this
.graph;
this
.graph = node;
}
addVertex(vk, source, destination) {
this
.addEdge(source, vk);
this
.addEdge(vk, destination);
}
printGraph() {
for
(let i = 0; i <
this
.v; ++i) {
let str = i +
" "
;
let temp =
this
.graph[i];
while
(temp !=
null
) {
str +=
"-> "
+ temp.vertex +
" "
;
temp = temp.next;
}
document.write(str +
"<br>"
);
}
}
delVertex(k) {
for
(let i = 0; i <
this
.v; ++i) {
let temp =
this
.graph[i];
if
(i === k) {
this
.graph[i] = temp.next;
temp =
this
.graph[i];
}
while
(temp !=
null
) {
if
(temp.vertex === k) {
break
;
}
let prev = temp;
temp = temp.next;
if
(temp ==
null
) {
continue
;
}
prev.next = temp.next;
temp =
null
;
}
}
}
}
const V = 6;
const graph =
new
AdjList(V);
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(3, 2);
graph.addEdge(4, 3);
document.write(
"Initial adjacency list<br>"
);
graph.printGraph();
graph.addVertex(5, 3, 2);
document.write(
"Adjacency list after adding vertex<br>"
);
graph.printGraph();
graph.delVertex(4);
document.write(
"Adjacency list after deleting vertex<br>"
);
graph.printGraph();
</script>