Java Code
import java.util.*;
class Graph {
int vertices;
LinkedList<Integer> adjacencyList[];
@SuppressWarnings("unchecked")
public Graph(int vertices) {
this.vertices = vertices;
adjacencyList = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adjacencyList[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination) {
this.adjacencyList[source].add(destination);
this.adjacencyList[destination].add(source); // comment this line for directed graph
}
public void printGraph() {
System.out.println("Adjacency List of Undirected Graph");
for (int i = 0; i < vertices; i++) {
System.out.print(i + " => ");
for(int nbr : adjacencyList[i]) {
System.out.print(nbr + " ");
}
System.out.println();
}
}
public static void main( String args[] ) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.printGraph();
}
}
Output:
Adjacency List of Undirected Graph 0 => 1 2 1 => 0 3 2 => 0 3 3 => 1 2
C++ Code:
#include<bits/stdc++.h>
using namespace std;
class Graph {
int vertices;
vector<int> *adjacencyList;
public:
Graph(int v) {
vertices = v;
adjacencyList = new vector<int>[vertices];
}
void addEdge(int source, int destination) {
adjacencyList[source].push_back(destination);
adjacencyList[destination].push_back(source); // comment this line for directed graph
}
void printGraph() {
cout << "Adjacency List of Undirected Graph" << endl;
for (int i = 0; i < vertices; i++) {
cout << i << " => ";
for(auto nbr : adjacencyList[i]) {
cout << nbr << " ";
}
cout << endl;
}
}
};
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.printGraph();
return 0;
}
Output:
Adjacency List of Undirected Graph 0 => 1 2 1 => 0 3 2 => 0 3 3 => 1 2
Python Code:
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.adjacency_list = [[] for i in range(self.vertices)]
def add_edge(self, source, destination):
self.adjacency_list[source].append(destination)
self.adjacency_list[destination].append(source) # comment this line for directed graph
def print_graph(self):
print("Adjacency List of Undirected Graph")
for i in range(self.vertices):
print(i, " => ", end = " ")
for nbr in self.adjacency_list[i]:
print(nbr, end = " ")
print()
if __name__ == '__main__':
g = Graph(4);
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
g.print_graph()
Output:
Adjacency List of Undirected Graph 0 => 1 2 1 => 0 3 2 => 0 3 3 => 1 2