Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Represent Graph Using Adjacency List
What is Adjacency List?
An adjacency list is a collection of unordered lists that are used to represent a finite graph. Each list in the collection represents one of the vertex of the graph and it will store the adjacent vertices of that vertex. Let's see an example:
Graph
The image below represent a simple undirected graph with 6 vertices and 8 edges.
Adjacency List
The adjacency list of the above graph is shown below.
Algorithm
The following are the steps to create (represent) a graph using an adjacency list:
- Step 1: Start
- Step 2: Input the number of vertices V and number of edges E in the graph
- Step 3: Create an array of lists (adjList[V]) to store adjacent vertices for each vertex
- Step 4: For each edge, repeat the steps 5,6 and 7.
- Step 5:Input the pair of vertices (u, v) that form an edge
- Step 6:Add v to the adjacency list of u
- Step 7:If the graph is undirected, also add u to the adjacency list of v
- Step 8: Display the adjacency list for each vertex
- Step 9: End
C++ Program to Create Adjacency List
The following C++ program demonstrates how to create an adjacency list for a graph. The program allows the user to input the number of vertices and edges, and then it displays the adjacency list.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int V, E;
bool isDirected;
// Step 1 & 2: Input vertices and edges
cout << "Enter number of vertices: ";
cin >> V;
cout << "Enter number of edges: ";
cin >> E;
cout << "Is the graph directed? (1 for Yes, 0 for No): ";
cin >> isDirected;
// Step 3: Create adjacency list
vector<int> adjList[V];
// Step 4: Input edges
for (int i = 0; i < E; i++) {
int u, v;
cout << "Enter edge " << i + 1 << " (format: u v): ";
cin >> u >> v;
adjList[u].push_back(v);
if (!isDirected) {
adjList[v].push_back(u);
}
}
// Step 5: Display adjacency list
cout << "\nAdjacency List:\n";
for (int i = 0; i < V; i++) {
cout << i << " ? ";
for (int neighbor : adjList[i]) {
cout << neighbor << " ";
}
cout << endl;
}
// Step 6: End
return 0;
}
Sample Output
The output of the above program is as follows:

Advertisements