fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to add an edge to the graph
  5. void addEdge(vector<vector<int>> &adjList, int u, int v) {
  6. adjList[u].push_back(v); // Add v to u's list
  7. adjList[v].push_back(u); // Add u to v's list (for an undirected graph)
  8. }
  9.  
  10. // Function to print the adjacency list representation of the graph
  11. void printGraph(const vector<vector<int>> &adjList) {
  12. for (int i = 0; i < adjList.size(); i++) {
  13. cout << "Vertex " << i << ":";
  14. for (int j : adjList[i]) {
  15. cout << " -> " << j;
  16. }
  17. cout << endl;
  18. }
  19. }
  20.  
  21. int main() {
  22. int numVertices = 5; // Number of vertices in the graph
  23.  
  24. // Create an adjacency list
  25. vector<vector<int>> adjList(numVertices);
  26.  
  27. // Add edges
  28. addEdge(adjList, 0, 1);
  29. addEdge(adjList, 0, 4);
  30. addEdge(adjList, 1, 2);
  31. addEdge(adjList, 1, 3);
  32. addEdge(adjList, 1, 4);
  33. addEdge(adjList, 2, 3);
  34. addEdge(adjList, 3, 4);
  35.  
  36. // Print the adjacency list
  37. printGraph(adjList);
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Vertex 0: -> 1 -> 4
Vertex 1: -> 0 -> 2 -> 3 -> 4
Vertex 2: -> 1 -> 3
Vertex 3: -> 1 -> 2 -> 4
Vertex 4: -> 0 -> 1 -> 3