File tree Expand file tree Collapse file tree
CPP/data_structures/trees Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ * Graph Adjacency List Implementation
3+ *
4+ * Description:
5+ * This program implements an undirected graph using an adjacency list representation.
6+ * Each vertex maintains a list of its adjacent vertices. The graph supports adding edges
7+ * between vertices and printing the complete adjacency list structure.
8+ *
9+ * Time Complexity:
10+ * - addEdge(): O(1) - Constant time insertion at the end of the list
11+ * - print(): O(V + E) - where V is the number of vertices and E is the number of edges
12+ *
13+ * Space Complexity:
14+ * - O(V + E) - Stores V adjacency lists with a total of 2E entries (each edge stored twice)
15+ *
16+ * Author: @Enimi-dev
17+ */
18+
19+ #include < iostream>
20+ #include < list>
21+ #include < vector>
22+ class Graph {
23+ int v; // Number of vertices in the graph
24+ std::list<int > *arr; // Array of lists to represent adjacency list
25+ public:
26+ Graph (int val) { // Constructor to initialize the graph with 'val' vertices
27+ this ->v = val;
28+ arr = new std::list<int >[v];
29+ }
30+ void addEdge (int u, int v) { // Add an undirected edge between vertex u and vertex v
31+ arr[v].push_back (u);
32+ arr[u].push_back (v);
33+ }
34+ void print () { // Print the adjacency list representation of the graph
35+ for (int i=0 ; i<v; i++) {
36+ std::cout << i << " : " ;
37+ for (auto val: arr[i]) {
38+ std::cout<<val<<" " ;
39+ }
40+ std::cout<<std::endl;
41+ }
42+ }
43+ };
44+ int main () {
45+ Graph g (5 ); // Create a graph with 5 vertices (0 to 4)
46+ g.addEdge (0 , 1 );
47+ g.addEdge (1 , 2 );
48+ g.addEdge (1 , 3 );
49+ g.addEdge (2 , 3 );
50+ g.addEdge (2 , 4 );
51+
52+ g.print ();
53+
54+ return 0 ;
55+ }
You can’t perform that action at this time.
0 commit comments