graph using adjacency list code example
Example 1: graph c++
#include <bits/stdc++.h>
using namespace std;
class graph
{
vector<int>*adjacency_list;
int Vertices;
public:
graph(int n)
{
Vertices=n;
adjacency_list=new vector<int>[Vertices];
}
void add_edge(int,int);
void display_graph();
};
int main()
{
graph g1(5);
g1.add_edge(0,1);
g1.add_edge(1,2);
g1.add_edge(1,3);
g1.add_edge(2,4);
g1.add_edge(2,3);
cout<<"The entered Graph is "<<endl;
g1.display_graph();
return 0;
}
void graph::add_edge( int u,int v )
{
if( u >= Vertices || v >= Vertices )
{
cout<<"Overflow"<<endl;
return;
}
if( u<0 || v<0 )
{
cout<<"underflow"<<endl;
return;
}
adjacency_list[u].push_back(v);
adjacency_list[v].push_back(u);
}
void graph::display_graph()
{
for(int i=0;i<Vertices;i++)
{
cout<<"Adjacency list of vertex of vertex "<<i<<endl;
for(auto it:adjacency_list[i])
{
cout<<it<<" ";
}
cout<<endl;
}
}
Example 2: adjacency list representation of graph
#include <iostream>
using namespace std;
#define v 5
class node
{
public:
int data;
node*next;
};
node*adjlist[v];
void init()
{
for(int i=0;i<v;i++)
{
adjlist[i]=NULL;
}
}
void addedge(int str,int en)
{
node*temp=new node;
temp->data=en;
temp->next=adjlist[str];
adjlist[str]=temp;
}
void hasedge(int str,int en)
{
node*temp=new node;
temp=adjlist[str];
while(temp!=NULL)
{
if(temp->data==en)
{
cout<<"yes:";
}
temp=temp->next;
}
}
void remove(int str,int en)
{
if(adjlist[str]==NULL)
{
return;
}
if(adjlist[str]->data==en)
{
node*temp=new node;
temp=adjlist[str];
adjlist[str]=adjlist[str]->next;
delete temp;
}
else
{
node *ptr=new node;
ptr=adjlist[str];
while(ptr->next!=NULL)
{
node*temp=new node;
if(ptr->next->data==en)
{
temp=ptr->next;
ptr->next=ptr->next->next;
delete temp;
break;
}
ptr=ptr->next;
}
}
}
void display()
{
for(int i=0;i<v;i++)
{
node*temp=new node;
cout<<"adjlist[]"<<i<<endl;
temp=adjlist[i];
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
}
int main()
{
init();
addedge(0,1);
addedge(0,2);
addedge(0,3);
addedge(1,3);
addedge(1,4);
addedge(2,3);
addedge(3,4);
display();
hasedge(0,3);
hasedge(0,4);
remove(0,1);
remove(1,4);
display();
return 0;
}