0

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;
    }
  }
}
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
  • Hm, why would you need linked lists, though? If you're writing a graph then your Node class will have an array of outbound connections, not "a single next"? Also, if you're encoding the values in the nodes themselves, you don't even need a dedicated edge class (if you're modeling a DFA graph, though, your want to encode the values on the edges, and keep the nodes bare, so then having Node + Edge makes sense) – Mike 'Pomax' Kamermans Aug 02 '19 at 03:43
  • Possible duplicate of [How to access array of linked list?](https://stackoverflow.com/questions/13781412/how-to-access-array-of-linked-list) – Abhinav Kinagi Aug 02 '19 at 03:45
  • 1
    DO NOT name your class`List`, this conflicts with the `java.util.List`class from the Java library. Overloading a Java class will just cause headaches later for you and whoever has to maintain your code. – Jim Garrison Aug 02 '19 at 04:15

0 Answers0