Skip to content

Commit 0daa8cb

Browse files
authored
Create 03 - Adjacency List - Hashmap.cpp
1 parent b8dabc3 commit 0daa8cb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <iostream>
2+
#include <unordered_map>
3+
#include <list>
4+
using namespace std;
5+
6+
// Graph Class Definition
7+
class Graph {
8+
public:
9+
unordered_map<int, list<int>> adjacencyList; // To store adjacency list
10+
11+
// Add an edge to the graph
12+
void addEdge(int sourceNode, int destinationNode, bool isDirected) {
13+
// Add the edge from source to destination
14+
adjacencyList[sourceNode].push_back(destinationNode);
15+
16+
// If the graph is undirected, add the reverse edge
17+
if (!isDirected) {
18+
adjacencyList[destinationNode].push_back(sourceNode);
19+
}
20+
}
21+
22+
// Print the adjacency list of the graph
23+
void printGraph() {
24+
for (auto vertex : adjacencyList) {
25+
cout << vertex.first << " -> ";
26+
for (auto neighbor : vertex.second) {
27+
cout << neighbor << ", ";
28+
}
29+
cout << endl;
30+
}
31+
}
32+
};
33+
34+
int main() {
35+
int numberOfNodes;
36+
cout << "Enter the number of nodes in the graph:" << endl;
37+
cin >> numberOfNodes;
38+
39+
int numberOfEdges;
40+
cout << "Enter the number of edges in the graph:" << endl;
41+
cin >> numberOfEdges;
42+
43+
Graph graphInstance; // Create a Graph object
44+
45+
// Input edges
46+
for (int i = 0; i < numberOfEdges; i++) {
47+
int sourceNode, destinationNode;
48+
cin >> sourceNode >> destinationNode;
49+
50+
// Add the edge to the graph (default: undirected)
51+
graphInstance.addEdge(sourceNode, destinationNode, false);
52+
}
53+
54+
// Print the graph representation
55+
graphInstance.printGraph();
56+
57+
return 0;
58+
}

0 commit comments

Comments
 (0)