数据结构_图_拓扑排序
head.h
#include<iostream>
using namespace std;
#define MAX_VEX_NUM 20
class ArcNode //弧节点
{
public:
ArcNode();
int tailnode;
ArcNode *next;
};
ArcNode::ArcNode()
{
next = NULL;
}
class VexNode //顶点节点
{
public:
VexNode();
char name;
int indegree;
ArcNode *firstarc;
};
VexNode::VexNode()
{
indegree = 0;
firstarc = NULL;
}
class VexBox //顶点集合
{
public:
VexBox();
VexNode vexbox[MAX_VEX_NUM];
int vexnum;
};
VexBox::VexBox()
{
vexnum = 0;
}
class TPSort //拓扑排序类
{
public:
void GetTPSquence(); //接口函数
private:
void GetVex(); //得到顶点信息
void GetArc(); //得到弧信息
void TPSorting(); //拓扑排序
VexBox v;
};
void TPSort::GetTPSquence() //接口函数
{
GetVex(); //得到顶点信息
GetArc(); //得到弧信息
TPSorting(); //拓扑排序
}
void TPSort::GetVex() //得到顶点信息
{
cout << "Please Input The Name Of Each Vertex :" << endl << endl;
char name;
while (cin >> name)
{
v.vexbox[v.vexnum++].name = name;
}
cin.clear();
}
void TPSort::GetArc() //得到弧信息
{
cout << "Please Input The Tail And Head Of Each Arc :" << endl << endl;
int vex1, vex2;
ArcNode *newnode, *p;
while (cin >> vex1 >> vex2)
{
newnode = new ArcNode;
newnode->tailnode = vex2;
v.vexbox[vex2].indegree++;
if ((p = v.vexbox[vex1].firstarc) == NULL)
{
v.vexbox[vex1].firstarc = newnode;
}
else
{
while (p->next != NULL)
p = p->next;
p->next = newnode;
}
}
cin.clear();
}
void TPSort::TPSorting() //拓扑排序
{
int count = 0;
bool find = false;
ArcNode *p;
while (1)
{
for (int i = 0; i < v.vexnum; i++)
{
if (v.vexbox[i].indegree == 0) //删除入度为零
{
v.vexbox[i].indegree--;
cout << v.vexbox[i].name << endl;
find = true;
count++;
p = v.vexbox[i].firstarc;
while (p != NULL) //相关顶点的入度减一
{
v.vexbox[p->tailnode].indegree--;
p = p->next;
}
break;
} //if
} //for
if (find == false)
break;
else
find = false;
} //while
if (count == v.vexnum)
cout << "This Is A Acycline Graph :" << endl << endl; //无环图
else
cout << "This Is A Cycling Graph :" << endl << endl; //有环
} //TPSorting
main.cpp
#include"head.h"
int main()
{
TPSort tp;
tp.GetTPSquence();
system("pause");
}