数据结构->有向图邻接表的创建(纯小白向)
适合纯新手向理解有向图的创建分析
有向图的邻接表创建和无向图的邻接表创建类似,甚至步骤更加简单
#include<iostream>
#define maxSize 30
using namespace std;
typedef struct ArcNode {
int adjvex;
struct ArcNode *nextarc;
} ArcNode;
typedef struct {
int data;
ArcNode *firstarc;
} Vnode;
//可以利用结构体整体结构,也可以拆分结构体变为单独搜索
typedef struct {
Vnode adjlist[maxSize];
int n, e;//n数目 e边数
} AGraph;
AGraph *graph;
void create() {
graph = new AGraph;
cout << "输入顶点的数目: " << endl;
cin >> graph->n;
cout << "输入图中边的数目: " << endl;
cin >> graph->e;
int u = -1, v = -1;
for(int i = 0; i < graph->n ; i++) {
graph->adjlist[i].data = i;
graph->adjlist[i].firstarc = NULL;
}
ArcNode *node;
for(int i = 0 ; i < graph->e ; i++){
cout<<"输入一条边上两个点的数字信息(u,v)(u表示头节点,v表示尾节点)"<<endl;
cin>>u>>v;
node = new ArcNode;
node->adjvex = v;
node->nextarc = nullptr;
if(graph->adjlist[u].firstarc==nullptr){
graph->adjlist[u].firstarc = node;
}
else{
//头插法
node->nextarc = graph->adjlist[u].firstarc->nextarc;
graph->adjlist[u].firstarc->nextarc = node;
}
}
}
void travseTree() {
for(int i = 0; i < graph->n; i++) {
if(graph->adjlist[i].firstarc != NULL) {
cout <<"与"<< i << "连接的点有:"<<" ";
ArcNode *p = graph->adjlist[i].firstarc;
while(p != NULL) {
cout << p->adjvex << " -> ";
p = p->nextarc;
}
cout << endl;
}
}
}
int main(void) {
create();
travseTree();
return 0;
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)