Adjacency List representation in a graph in c++ Data Structure


#include<bits/stdc++.h>
using namespace std;

void edge(vector<int>adj[], int u, int v){
    adj[u].push_back(v);
    adj[v].push_back(u);
}

void printGraph(vector<int> adj[], int v){
    for (int i = 0; i < v; i++){
        cout << "Adjaceny list " << i <<"\nhead ";
        for(auto x:adj[i]){
            cout << "->" << x ;
        }
        cout << endl;
    }
}

int main(){

    int v = 5;
    vector<int> adj[v];
    edge(adj, 0, 1);
    edge(adj, 0, 4);
    edge(adj, 1, 2);
    edge(adj, 1,3);
    edge(adj, 1, 4);
    edge(adj, 2,3);
    edge(adj, 3,4);
    printGraph(adj, v);
}



Output is :

Adjaceny list 0 head ->1->4 Adjaceny list 1 head ->0->2->3->4 Adjaceny list 2 head ->1->3 Adjaceny list 3 head ->1->2->4 Adjaceny list 4 head ->0->1->3

Post a Comment

0 Comments