C++ program to convert adjacency matrix to adjacency list.
C++ program to convert adjacency matrix to adjacency list
#include<iostream>
using namespace std;
struct graphnode
{
int ver_no;
graphnode *next;
};
class graph
{
int a[10][10],n;
graphnode *ver[10];
public:
graph()
{
for(int i=0;i<10;i++)
ver[i]=NULL;
}
void getdata();
void display_list();
void matrix_to_list();
};
void graph::getdata()
{
cout<<"Enter the number of vertices ";
cin>>n;
cout<<"Enter the adjacency matrix\n";
for(int i=0;i<n;i++)
for(int y=0;y<n;y++)
cin>>a[i][y];
}
void graph::matrix_to_list()
{
graphnode *ne,*temp;
for(int i=0;i<n;i++)
{
for(int y=0;y<n;y++)
{
if(a[i][y]!=0)
{
ne=new graphnode;
ne->ver_no=y;
ne->next=NULL;
if(ver[i]==NULL)
{
ver[i]=ne;
temp=ne;
}
else
{
temp->next=ne;
temp=temp->next;
}
}
}
}
}
void graph::display_list()
{
graphnode *temp;
cout<<endl<<"Adjacency List successfully created : "<<endl;
for(int i=0;i<n;i++)
{
temp=ver[i];
cout<<i<<" -> ";
while(temp->next!=NULL)
{
cout<<temp->ver_no<<" -> ";
temp=temp->next;
}
cout<<temp->ver_no<<endl;
}
}
int main()
{
graph list;
list.getdata();
list.matrix_to_list();
list.display_list();
return 0;
}
using namespace std;
struct graphnode
{
int ver_no;
graphnode *next;
};
class graph
{
int a[10][10],n;
graphnode *ver[10];
public:
graph()
{
for(int i=0;i<10;i++)
ver[i]=NULL;
}
void getdata();
void display_list();
void matrix_to_list();
};
void graph::getdata()
{
cout<<"Enter the number of vertices ";
cin>>n;
cout<<"Enter the adjacency matrix\n";
for(int i=0;i<n;i++)
for(int y=0;y<n;y++)
cin>>a[i][y];
}
void graph::matrix_to_list()
{
graphnode *ne,*temp;
for(int i=0;i<n;i++)
{
for(int y=0;y<n;y++)
{
if(a[i][y]!=0)
{
ne=new graphnode;
ne->ver_no=y;
ne->next=NULL;
if(ver[i]==NULL)
{
ver[i]=ne;
temp=ne;
}
else
{
temp->next=ne;
temp=temp->next;
}
}
}
}
}
void graph::display_list()
{
graphnode *temp;
cout<<endl<<"Adjacency List successfully created : "<<endl;
for(int i=0;i<n;i++)
{
temp=ver[i];
cout<<i<<" -> ";
while(temp->next!=NULL)
{
cout<<temp->ver_no<<" -> ";
temp=temp->next;
}
cout<<temp->ver_no<<endl;
}
}
int main()
{
graph list;
list.getdata();
list.matrix_to_list();
list.display_list();
return 0;
}
No comments:
Post a Comment