#include<iostream>
#include<cstdio>
using namespace std;
#define MAX 105
#define maxSize 1000
int adj[MAX][MAX]={0};
typedef struct ArcNode
{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct
{
int data;
ArcNode *firstarc;
}Vnode;
typedef struct
{
Vnode adjlist[maxSize];
int n,e;
}AGraph;
AGraph *graph;
void insertNode(ArcNode *node,ArcNode *newnode)
{
ArcNode *p=node;
while(p->nextarc!=NULL) p=p->nextarc;
//找到最后
p->nextarc=newnode;
}
void create_Graph()
{
graph=(AGraph*)malloc(sizeof(AGraph));
cout<<"请输入图G中结点与边的数量:";
cin>>graph->n>>graph->e;
int u=-1,v=-1;
//首先初始化一下图结点
for(int i=0;i<graph->n;i++) graph->adjlist[i].firstarc=NULL;
ArcNode* node;
for(int i=0;i<graph->e;i++)
{
cout<<"请输入联通点A与B:";
cin>>u>>v;
//申请空间并且初始
node=(ArcNode*)malloc(sizeof(ArcNode));
node->adjvex=v;
node->nextarc=NULL;
graph->adjlist[u].data=u;
//如果这个结点没有创建边,直接创头结点
if(graph->adjlist[u].firstarc==NULL)
graph->adjlist[u].firstarc = node;
//如果此时已经创建过了,直接插入即可
else insertNode(graph->adjlist[u].firstarc,node);
}
}
void travse_Graph()
{
for(int i=0;i<graph->n;i++)
{
if(graph->adjlist[i].firstarc!=NULL)
{
cout<<"在图G中与"<<i<<"连接的点有:";
ArcNode *p=graph->adjlist[i].firstarc;
while(p)
{
cout<<p->adjvex<<" ";
p=p->nextarc;
}
cout<<endl;
}
}
}
void get_neighbor_matrix()
{
int n,m;//n条边,m个结点
int x,y;
cout<<"请输入图中边与结点的个数:";
cin>>n>>m;
for(int i=0;i<n;i++)
{
cout<<"请你输入结点之间存在的关系:";
cin>>x>>y;
//元素从1开始,数组从0开始
//邻接矩阵对称
adj[x-1][y-1]=1;
adj[y-1][x-1]=1;
}
cout<<"该图G的邻接矩阵可以表示为:"<<endl;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++) cout<<adj[i][j]<<" ";
cout<<endl;
}
}
void get_neighbor_table()
{
create_Graph();
travse_Graph();
}
int main()
{
cout<<"************实现临接矩阵操作************"<<endl;
get_neighbor_matrix();
cout<<"************实现单向临接表操作************"<<endl;
get_neighbor_table();
return 0;
}
邻接矩阵与邻接链表的算法操作实现
最新推荐文章于 2024-10-11 16:56:17 发布