有向图的邻接表创建和无向图的邻接表创建类似,甚至步骤更加简单
#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;
}