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: Oriented and unoriented graphs C++
#include <iostream>
using namespace std;
struct adjNode {
int val, cost;
adjNode* next;
};
struct graphEdge {
int start_ver, end_ver, weight;
};
class DiaGraph{
adjNode* getAdjListNode(int value, int weight, adjNode* head) {
adjNode* newNode = new adjNode;
newNode->val = value;
newNode->cost = weight;
newNode->next = head;
return newNode;
}
int N;
public:
adjNode **head;
DiaGraph(graphEdge edges[], int n, int N) {
head = new adjNode*[N]();
this->N = N;
for (int i = 0; i < N; ++i)
head[i] = nullptr;
for (unsigned i = 0; i < n; i++) {
int start_ver = edges[i].start_ver;
int end_ver = edges[i].end_ver;
int weight = edges[i].weight;
adjNode* newNode = getAdjListNode(end_ver, weight, head[start_ver]);
head[start_ver] = newNode;
}
}
~DiaGraph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
void display_AdjList(adjNode* ptr, int i)
{
while (ptr != nullptr) {
cout << "(" << i << ", " << ptr->val
<< ", " << ptr->cost << ") ";
ptr = ptr->next;
}
cout << endl;
}
int main()
{
graphEdge edges[] = {
{0,1,2},{0,2,4},{1,4,3},{2,3,2},{3,1,4},{4,3,3}
};
int N = 6;
int n = sizeof(edges)/sizeof(edges[0]);
DiaGraph diagraph(edges, n, N);
cout<<"Graph adjacency list "<<endl<<"(start_vertex, end_vertex, weight):"<<endl;
for (int i = 0; i < N; i++)
{
display_AdjList(diagraph.head[i], i);
}
return 0;
}