#include <iostream>
#include <stack>
using namespace std;
#define MAX_VERTEX_NUM 26
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
ArcNode(){nextarc=NULL;}
}ArcNode;//链表中的节点
typedef struct VNode{
// int data;
ArcNode *firstarc;
VNode(){firstarc=NULL;}
}VNode,AdjList[MAX_VERTEX_NUM];//图数组和单数组节点
typedef struct{
AdjList vertices;
int vexnum,arcnum;
}ALGraph;//保存整个图结构的信息
ALGraph graph;
int in_degree[MAX_VERTEX_NUM];
void CreatGraph(){
cin>>graph.vexnum>>graph.arcnum;
for(int i=0;i<graph.arcnum;i++){
ArcNode *temp1=new ArcNode;
// ArcNode *temp2=new ArcNode;
int x,y;cin>>x>>y;
temp1->adjvex=y;temp1->nextarc=NULL;
// temp2->adjvex=x;temp2->nextarc=NULL;
if(!graph.vertices[x].firstarc) graph.vertices[x].firstarc=temp1;
else{
temp1->nextarc=graph.vertices[x].firstarc;
graph.vertices[x].firstarc=temp1;
}
/* if(!graph.vertices[y].firstarc) graph.vertices[y].firstarc=temp2;
else{
temp2->nextarc=graph.vertices[y].firstarc;
graph.vertices[y].firstarc=temp2;
}*/
// in_degree[x]++;
in_degree[y]++;
}
}
void TopologicalSort()
{
stack<int> S;
for(int i=1;i<=graph.vexnum;i++){if(!in_degree[i]) S.push(i);}
while(!S.empty()){
int i=S.top();S.pop();
cout<<i<<" ";
ArcNode *temp=graph.vertices[i].firstarc;
while(temp){
in_degree[temp->adjvex]--;
if(!in_degree[temp->adjvex]) S.push(temp->adjvex);
temp=temp->nextarc;
}
}
}
int main(void){
CreatGraph();
TopologicalSort();
return 0;
}
05-25
2万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-12
3万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-07
3785
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-08
963
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)