Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an array of linked lists in java?

So I need to take in input of edges of a bipartite graph like this:

6
1 3
1 2
1 5
2 7
2 4
2 9

The first number is the number of edges. After that edges are listed. See how for example vertex 1 has multiple different edges and I want to keep track of what 1 is connected to, I was thinking that each vertex of the graph would have some sort of list of vertices it is connected to which leads me to try to create an array of linked lists but I'm not sure how I would do that. I tried

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0, m = 6;
while(i!=m){
    int temp = sc.nextInt();
    int temp2 = sc.nextInt();
    vertex[temp].add(temp2);
    i++;
}

But I get a nullpointerexception at the add line.

like image 885
user2923535 Avatar asked Nov 25 '13 20:11

user2923535


People also ask

Can you create an array of linked lists in Java?

A linked list is a sequence of data structures, which are connected together via links. To create an array of linked lists, create required linked lists and, create an array of objects with them.

Can you have an array of linked lists?

An array of linked lists is an important data structure that can be used in many applications. Conceptually, an array of linked lists looks as follows. An array of linked list is an interesting structure as it combines a static structure (an array) and a dynamic structure (linked lists) to form a useful data structure.

How do you add an array to a linked list in Java?

You can just have a list of Interger arrays: LinkedList <int[]> main_list = new LinkedList <>(); int[] arr = {0,1}; int[] arr2 = {2,3}; main_list. add(arr); main_list. add(arr2);


1 Answers

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0, m = 6;
while(i!=m){
  int temp = sc.nextInt();
  int temp2 = sc.nextInt();

  // Make sure the list is initialized before adding to it
  if (vertex[temp] == null) {
     vertex[temp] = new LinkedList<Integer>();
  }

  vertex[temp].add(temp2);
  i++;
}
like image 66
Stefan Haustein Avatar answered Sep 24 '22 14:09

Stefan Haustein