educative.io

Educative

Why a vertex is added to the head of the Linked List in this Adjacency List code?

I am not sure what’s the login behind using insertAtHead instead of insertAtTail ?
Here is the code:

 addEdge(source, destination) {

     if (source < this.vertices && destination < this.vertices)

     //Since we are implementing a directed list, (0,1) is not the same as (1,0)

     this.list[source].insertAtHead(destination);

     //If we were to implement an undirected graph where (0,1)==(1,0),

     //we would create an additional edge from destination to source too:

     //this.list[destination].insertAtHead(source);

   }

Course: Data Structures for Coding Interviews in JavaScript - Learn Interactively
Lesson: Graph Implementation - Data Structures for Coding Interviews in JavaScript

Hi @ks1
Thanks for reaching out to us. The code in the lesson is just provided for the implementation purpose.

Hope it will help, Happy Learning :slight_smile: