-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacencyList.java
More file actions
36 lines (35 loc) · 956 Bytes
/
AdjacencyList.java
File metadata and controls
36 lines (35 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;
public class AdjacencyList {
int edges;
int vertices;
List<Integer>[] adjList;
public AdjacencyList(int v){
this.vertices = v;
this.edges = 0;
adjList = new List[v];
for(int i=0; i<v; i++){
adjList[i] = new ArrayList<>();
}
}
public void addEdge(int u, int v){
adjList[u].add(v);
adjList[v].add(u);
edges++;
}
public static void main(String[] args){
AdjacencyList graph = new AdjacencyList(5);
graph.addEdge(0, 1);
graph.addEdge(0, 4);
graph.addEdge(1, 4);
graph.addEdge(1, 3);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
for(int i=0; i<graph.vertices; i++){
System.out.print(i + ": ");
for(int neighbor : graph.adjList[i]){
System.out.print(neighbor + " ");
}
System.out.println();
}
}
}