-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdjacencyListGraph.java
More file actions
79 lines (69 loc) · 1.84 KB
/
AdjacencyListGraph.java
File metadata and controls
79 lines (69 loc) · 1.84 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package datastructure.graph;
import java.util.LinkedList;
/**
* The type Adjacency list graph.
*/
public class AdjacencyListGraph implements Graph {
/**
* The Vertices.
*/
public int vertices;
/**
* The Adjacency list.
*/
public LinkedList<Integer> adjacencyList[];
/**
* Instantiates a new Adjacency list graph.
*
* @param vertices the vertices
*/
public AdjacencyListGraph(int vertices) {
this.vertices = vertices;
adjacencyList = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adjacencyList[i] = new LinkedList<>();
}
}
/**
* Print graph.
*/
@Override
public void printGraph() {
System.out.println("Adjacency List of Directed Graph");
for (int i = 0; i < vertices; i++) {
if (adjacencyList[i] != null) {
System.out.print("|" + i + "| => ");
for (int j = 0; j < adjacencyList[i].size(); j++) {
System.out.print("[" + adjacencyList[i].get(j) + "] -> ");
}
System.out.println("null");
} else {
System.out.println("|" + i + "| => " + "null");
}
}
}
/**
* Add edge.
*
* @param source the source
* @param destination the destination
*/
@Override
public void addEdge(int source, int destination) {
if (source < vertices && destination < vertices)
adjacencyList[source].addLast(destination);
}
/**
* Main.
*
* @param args the args
*/
public static void main( String args[] ) {
AdjacencyListGraph g= new AdjacencyListGraph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.printGraph();
}
}