Grokking Graph Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Full Implementation defers from the previous provided implementation for add Edges

solomononaiwu

Feb 6, 2025

    public void addEdge(int vertex1, int vertex2) {         adjacencyList.get(vertex1).add(vertex2);         adjacencyList.get(vertex2).add(vertex1);     }

There is no check here to know if the vertex exists or not.

should be

    public void addEdge(int vertex1, int vertex2) {

   if( !adjacencyList.containsKey(vertex1) ){
        adjacencyList.put(vertex1,new ArrayList());
   }

        adjacencyList.get(vertex1).add(vertex2);

   if( !adjacencyList.containsKey(vertex2) ){
        adjacencyList.put(vertex2,new ArrayList());
   }

        adjacencyList.get(vertex2).add(vertex1);     }

1

0

Comments
Comments

On this page

Implementing the ADT operations

  1. add_vertex(vertex)
  1. add_edge(vertex1, vertex2)

A complete executable example