邻接矩阵与邻接链表的算法操作实现

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温柔济沧海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值