To add a vertex, we can simply add a key to the hash table. The same with removal -- we'll just remove the key. However, with removal, there is the caveat that we also need to ensure that the node to be removed is also disregarded as a neighbor of other nodes.
In other words, if node A
is a neighbor of B
, and node A
is to be removed, we should update B
's adjacency list.
xxxxxxxxxx
18
addVertex(nodeVal) {
this.adjacencyList.set(nodeVal, []);
// set a key with the node value,
// and an array to contain neighbors
}
​
removeVertex(val) {
if (this.adjacencyList.get(val)) {
this.adjacencyList.delete(val);
}
​
this.adjacencyList.forEach((vertex) => {
const neighborIdx = vertex.indexOf(val);
if (neighborIdx >= 0) {
vertex.splice(neighborIdx, 1);
}
})
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment