-
Notifications
You must be signed in to change notification settings - Fork 2
/
AdjacencyListRepresentation.java
59 lines (48 loc) · 1.55 KB
/
AdjacencyListRepresentation.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package Graph;
import java.util.LinkedList;
/**
* @author kalpak
*
* Adjacency List Representation
*
*/
public class AdjacencyListRepresentation {
int numOfVertex;
LinkedList<Integer> list[];
public AdjacencyListRepresentation(int numOfVertex) {
this.numOfVertex = numOfVertex;
// Initialize the adjacency list
list = new LinkedList[numOfVertex];
for (int i = 0; i < numOfVertex ; i++) {
list[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination){
//add edge
list[source].addFirst(destination);
//add back edge ((for undirected)
list[destination].addFirst(source);
}
public void printGraph(){
for (int i = 0; i < numOfVertex ; i++) {
if(list[i].size() > 0) {
System.out.print("Vertex " + i + " is connected to: ");
for (int j = 0; j < list[i].size(); j++) {
System.out.print(list[i].get(j) + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
AdjacencyListRepresentation GraphAdjacencyList = new AdjacencyListRepresentation(5);
GraphAdjacencyList.addEdge(0, 1);
GraphAdjacencyList.addEdge(0, 4);
GraphAdjacencyList.addEdge(1, 2);
GraphAdjacencyList.addEdge(1, 3);
GraphAdjacencyList.addEdge(1, 4);
GraphAdjacencyList.addEdge(2, 3);
GraphAdjacencyList.addEdge(3, 4);
GraphAdjacencyList.printGraph();
}
}