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;
    }
  }
}
3
  • 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) Commented Aug 2, 2019 at 3:43
  • Possible duplicate of How to access array of linked list? Commented Aug 2, 2019 at 3:45
  • 1
    DO NOT name your classList, this conflicts with the java.util.List<E>class from the Java library. Overloading a Java class will just cause headaches later for you and whoever has to maintain your code. Commented Aug 2, 2019 at 4:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.