有向图中反向图构造。对tinyDG.txt(http://pan.baidu.com/s/1o6jWtcA)文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。类名:GraphReverse。博文标题:第五周作业——有向图邻接表表示及反向图构造
邻接表表示示例如下:
0:1 5
1:
2:0 3
……
#include <iostream>
#include <fstream>
using namespace std;
struct ArcNode //定义边表节点
{
int adjvex;
ArcNode* next;
};
struct VertexNode //定义顶点表节点
{
int vertex;
ArcNode* firstedge;
};
class GraphReverse
{
public:
GraphReverse(char const * inFileName);
~GraphReverse();
void output(char const * forwardOutName ,char const * reversrOutName);//输出邻接表
private:
int vertexNum,arcNum; //顶点,边
VertexNode* adjlist; //正向邻接表
VertexNode* adjlist_reverse; //反向邻接表
};
int main(int argc, char const *argv[])
{
char const * inFileName= "tinyDG.txt";
char const * forwardOutName = "tinyDG_matrix_forwardOut.txt";
char const * reversrOutName = "tinyDG_matrix_reversrOut.txt";
GraphReverse graph(inFileName);
graph.output(forwardOutName,reversrOutName);
return 0;
}
GraphReverse::GraphReverse(char const * inFileName)
{
ifstream inFile(inFileName);
inFile >> vertexNum >> arcNum;
adjlist =new VertexNode[vertexNum];
adjlist_reverse =new VertexNode[vertexNum];
int first[arcNum],second[arcNum];
int i = 0;
while(inFile>>first[i]>>second[i])
++i;
//正向
for (i = 0; i < vertexNum; ++i) //初始化顶点表
{
adjlist[i].vertex=i;
adjlist[i].firstedge = NULL;
}
for (i = 0; i < arcNum; ++i) //生成正向邻接表
{
ArcNode* s1 = new ArcNode;
s1->adjvex = second[i];
s1->next = adjlist[first[i]].firstedge;
adjlist[first[i]].firstedge = s1;
}
//反向
for (i = 0; i < vertexNum; ++i) //初始化顶点表
{
adjlist_reverse[i].vertex=i;
adjlist_reverse[i].firstedge = NULL;
}
for (i = 0; i < arcNum; ++i) //生成反向邻接表
{
ArcNode* s2 = new ArcNode;
s2->adjvex = first[i];
s2->next = adjlist_reverse[second[i]].firstedge;
adjlist_reverse[second[i]].firstedge = s2;
}
}
GraphReverse::~GraphReverse()
{
for (int i = 0; i < vertexNum; ++i)
{
ArcNode* tempArc = adjlist[i].firstedge;
while(tempArc)
{
ArcNode* tempArc2 = tempArc;
tempArc = tempArc->next;
delete tempArc2;
}
}
delete adjlist;
for (int i = 0; i < vertexNum; ++i)
{
ArcNode* tempArc = adjlist_reverse[i].firstedge;
while(tempArc)
{
ArcNode* tempArc2 = tempArc;
tempArc = tempArc->next;
delete tempArc2;
}
}
delete adjlist_reverse;
}
void GraphReverse::output(char const * forwardOutName ,char const * reversrOutName)
{
ofstream outFile(forwardOutName);
for (int i = 0; i < vertexNum; ++i)
{
outFile<<adjlist[i].vertex<<" :";
ArcNode* tempArc = adjlist[i].firstedge;
while(tempArc)
{
outFile<< tempArc->adjvex <<" ";
tempArc = tempArc->next;
}
outFile<<endl;
}
outFile.close();
outFile.clear();
outFile.open(reversrOutName);
for (int i = 0; i < vertexNum; ++i)
{
outFile<<adjlist[i].vertex<<" :";
ArcNode* tempArc = adjlist_reverse[i].firstedge;
while(tempArc)
{
outFile<< tempArc->adjvex <<" ";
tempArc = tempArc->next;
}
outFile<<endl;
}
outFile.close();
}
结果如下:
正向图的邻接表:
反向图的邻接表: