以p和q作为工作指针,p负责遍历原始邻接表,q用于创建反向邻接表的边结点。在遍历原始邻接表的过程中,反向邻接表的边界点就是一个由顶点i指向顶点p->node的边。
#include <iostream>
using namespace std;
struct ArcNode //边表
{
int node; //所指向的顶点的序号
ArcNode* next;
};
struct Vertex //顶点表
{
ArcNode* arc = NULL; //指向的边
};
void build_adjacency_list(Vertex *&adjacency_list, int n) //建立一个邻接表
{
int a, b;
ArcNode* p = NULL;
adjacency_list = new Vertex[n];
cin >> a >> b;
while (a >= 0 && b >= 0)
{
p = new ArcNode;
p->node = b;
p->next = adjacency_list[a].arc;
adjacency_list[a].arc = p;
cin >> a >> b;
}
}
Vertex* reverse_graph(Vertex adjancency_list[], int n) //建立反向邻接表
{
Vertex* adverse_adjancency_list = new Vertex[n]; //反向邻接表
ArcNode* p = NULL, * q = NULL;
for (int i = 0; i < n; i++)
{
p = adjancency_list[i].arc;
while (p != NULL)
{
q = new ArcNode;
q->node = i; //产生一个由顶点i指向顶点p->node的边
q->next = adverse_adjancency_list[p->node].arc;
adverse_adjancency_list[p->node].arc = q;
p = p->next;
}
}
return adverse_adjancency_list;
}
void traverse(Vertex adjancency_list[], int n) //遍历邻接表
{
ArcNode* p = NULL;
for (int i = 0; i < n; i++)
{
p = adjancency_list[i].arc;
cout << i << '\t';
while (p != NULL)
{
cout << p->node << '\t';
p = p->next;
}
cout << endl;
}
}
int main(void)
{
int n; //顶点的个数
cin >> n;
Vertex* adjacency_list = NULL;
build_adjacency_list(adjacency_list, n); //创建一个邻接表
cout << "Before reversing:" << endl;
traverse(adjacency_list, n); //遍历该邻接表
Vertex* adverse_adjancency_list = reverse_graph(adjacency_list, n); //创建一个该邻接表所对应的反向邻接表
cout << "After reversing:" << endl;
traverse(adverse_adjancency_list, n); //遍历该邻接表
return 0;
}