#include <stdio.h>
#include <stdlib.h>
#define Max_Vertex_Num 100
#define STACK_SIZE 30
typedef struct ArcNode{
int adjvex; //此題用不到
struct ArcNode *nextarc;//下一個節點
int weight;//權重-此題用不到
}ArcNode;
/*表頭節點*/
typedef struct VNode{
int vertex;//表頭數組的數據
ArcNode *firstarc;//表頭數組的表頭節點域
}VNode;
typedef VNode Adjlist[Max_Vertex_Num];//VNode構成的表頭節點數組
/*整個鄰接表*/
typedef struct{
Adjlist adjlist;//每個定點後面的鏈表,記錄關聯點
int vexnum,arcnum;//頂點數和邊數
}ALGraph;
/*棧*/
typedef struct{
int *base;
int *top; //棧頂指針
int size;
}seqStack;
int InitStack(seqStack *s){
s->base = (int *)malloc(STACK_SIZE* sizeof(seqStack));//動態分配30個單位的stack
//省略是否空間滿
s->top = s->base;//棧頂和棧尾相同,棧裏面沒有元素
s->size = STACK_SIZE;
return 1;
}
int Push(seqStack *s,int x){
*s->top = x;
s->top++;
return 1;
}
int Pop(seqStack *s,int *x){
if(s->top == s->base)return 0;
else{
s->top--;
*x = *s->top;
return 1;
}
}
int GetTop(seqStack *s, int *x){
if(s->top==s->base)
return 0;
else{
*x=*(s->top-1);
return 1;
}
}
int IsEmpty(seqStack *s){
if(s->top==s->base){
return 1;
}else{
return 0;
}
}
void FindIndegree(ALGraph *G,int indegree[])
{
int i;
ArcNode *p;
for(i = 0;i<G->vexnum ;i++)
{
indegree[i]=0;
}
for(i = 0;i<G->vexnum ;i++)
{
p = G->adjlist[i].firstarc;
while(p){
indegree[p->adjvex]++;
p=p->nextarc;
}/*while*/
}/*for*/
}/*end*/
void TopLogicalSort(ALGraph *G){
int i,k;
int count;
ArcNode *p;
int indegree[G->vexnum];
FindIndegree(G,indegree);
seqStack s;
InitStack(&s);
for(i = 0;i<G->vexnum;i++)
{
//入度爲0的頂點入棧
if(indegree[i]==0){
Push(&s,i);
}
}
count =0;
while(!IsEmpty(&s)){
Pop(&s,&i);
printf("%d ",G->adjlist[i].vertex);
++count;
for(p=G->adjlist[i].firstarc;p;p=p->nextarc)
{
k=p->adjvex;
if((--indegree[k]==0)){
Push(&s,k);
}/*if*/
}/*for*/
}/*while*/
/*迴路異常*/
if(count<G->vexnum){
exit(0);
}
}
int LocateVex(ALGraph *G,int u){
int i;
for(i = 0; i<G->vexnum;++i)
{
if(G->adjlist[i].vertex == u)
{
return i;
}
}
return -1;
}
void CreateALGraph(ALGraph *G,int gType)
{
ArcNode *p;
int i,j,k;
int v1,v2;
scanf("%d,%d",&G->vexnum,&G->arcnum); //輸入頂點數和邊數
if(gType==0)
{
for(k=0;k<G->vexnum;k++)
{
G->adjlist[k].vertex = k;
G->adjlist[k].firstarc = NULL;
}
k = 0;
while(k<G->arcnum){
scanf("%d,%d",&v1,&v2);
k++;
i = LocateVex(G,v1);
j = LocateVex(G,v2);
/*給第i的表頭添加數據是j的節點*/
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = j;
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
/*給第j的表頭添加數據是i的節點*/
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = i;
p->nextarc = G->adjlist[j].firstarc;
G->adjlist[j].firstarc = p;
}
}else{
for(k=0;k<G->vexnum;k++)
{
G->adjlist[k].vertex = k;
G->adjlist[k].firstarc = NULL;
}
k = 0;
while(k<G->arcnum){
scanf("%d,%d",&v1,&v2);
k++;
i = LocateVex(G,v1);
j = LocateVex(G,v2);
/*給第i的表頭添加數據是j的節點——有向圖,不需要給j添加i數據的節點了*/
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex = j;
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
}
}
}
int main()
{
ALGraph G;
CreateALGraph(&G,1);
TopLogicalSort(&G);
return 0;
}