I am trying to implement a graph with an adjacency list. I am trying to use an array of linked lists. Each index in my array is a vertex in the graph and each node in the linked list of that index is a adjacent vertex to the index vertex. The problem I am having is that I do not know how to access the head of a specific linked list. Also, I use an ascii conversion because my graph is made of char's.
I have tried adj[index].head but this does not work.
public class GraphDriver {
public static void main(String[] args) {
List N = new List(16);
N.addEdge('a','b');
N.addEdge('a','e');
N.addEdge('a','f');
N.addEdge('b','c');
}
}
And my adjacency list class:
public class List {
Node head;
//Node class
class Node{
char data;
Node next;
//constructor to create new node
Node(char d) {data=d;next=null;}
}
List adj[];
int n;
List(int n){
this.n=n;
adj = new List[n];
}
void addEdge(char a, char b) {
int index = a;
index = index-97;
Node newNode = new Node(b);
if(adj[index]==null) {
adj[index].head = newNode;
}else {
newNode.next = adj[index].head;
adj[index].head = newNode;
}
}
}