请直接跑代码
代码
#include <bits/stdc++.h>
using namespace std;
#define MAXVERTEX 15
typedef struct EdgeNode
{
int adjvertex;
int weight;
EdgeNode* next;
EdgeNode() {
next =NULL;
weight = 0;
adjvertex = -1;
}
}*NextNode;
typedef struct VertexNode
{
int data;
int in;
EdgeNode* firstEdge;
VertexNode() {
in = 0;
data = 0;
firstEdge = new EdgeNode;
}
}AdjList[MAXVERTEX];
typedef struct GraphAdjList
{
AdjList adjList;
int vertexesNum;
int edgesNum;
}*graphAdjList;
bool TopologicalSort(graphAdjList GAL)
{
int i;
int count=0;
EdgeNode* e;
int k;
stack<int> stack;
int topNum = 0;
for (i = 0; i < GAL->vertexesNum; i++)
{
if (GAL->adjList[i].in == 0)
{
stack.push(i);
}
}
while (!stack.empty())
{
topNum = stack.top();
stack.pop();
count++;
cout << GAL->adjList[topNum].data << endl;
for (e = GAL->adjList[topNum].firstEdge; e; e = e->next)
{
k = e->adjvertex;
if ((--GAL->adjList[k].in) == 0)
{
stack.push(k);
}
}
}
if (count < GAL->vertexesNum)
{
return false;
}
else
{
return true;
}
}
int main() {
graphAdjList temp=new GraphAdjList;
cout << "请输入顶点数:" << endl;
cin >> temp->vertexesNum;
cout << "请输入边数:" << endl;
cin >> temp->edgesNum;
for (int i = 0; i < temp->edgesNum; i++) {
int a_start=0, a_end=0;
cin >> a_start >> a_end;
temp->adjList[a_end].in++;
temp->adjList[a_end].data = a_end;
temp->adjList[a_start].data = a_start;
NextNode a_pos = temp->adjList[a_start].firstEdge;
NextNode a_add = new EdgeNode;
if (a_pos->adjvertex == -1) {
a_pos->adjvertex = a_end;
continue;
}
while (a_pos->next) {
a_pos = a_pos->next;
}
a_pos->next = a_add;
a_add->adjvertex = a_end;
}
TopologicalSort(temp);
return 0;
}
测试数据
拓扑排序样例:
顶点数 :11
边数:13
0 2
1 2
2 3
4 3
1 4
3 5
4 5
3 6
8 6
0 7
7 8
10 0
9 10
![标题](https://i-blog.csdnimg.cn/blog_migrate/a2ad9c60b70130efa73ad9392a8cfd45.jpeg)