代码
#include <stdio.h>
#define MAXV 20
typedef int InfoType;
typedef struct
{
int no;
InfoType info;
} VertexType;
typedef struct
{
int edges[MAXV][MAXV];
int n, e;
VertexType vexs[MAXV];
} MGraph;
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
InfoType info;
} ArcNode;
typedef int Vertex;
typedef struct Vnode
{
Vertex data;
int count;
ArcNode *firstarc;
} VNode;
typedef VNode AdjList[MAXV];
typedef struct
{
AdjList adjlist;
int n, e;
} ALGraph;
void MatToList(MGraph g, ALGraph *&G)
{
int i, j, n = g.n;
ArcNode *p;
G = new ALGraph;
for (i = 0; i < n; i++)
G->adjlist[i].firstarc = NULL;
for (i = 0; i < n; i++)
for (j = n - 1; j >= 0; j--)
if (g.edges[i][j] != 0)
{
p = new ArcNode;
p->adjvex = j;
p->info = g.edges[i][j];
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
}
G->n = n;
G->e = g.e;
}
void DispAdj(ALGraph *G)
{
int i;
ArcNode *p;
printf("邻接表:\n");
for (i = 0; i < G->n; i++) {
p = G->adjlist[i].firstarc;
printf("%3d: ", i);
while (p != NULL) {
printf("%3d", p->adjvex);
p = p->nextarc;
}
printf("\n");
}
}
void TopSort(ALGraph *G)
{
int i, j;
int St[MAXV], top = -1;
ArcNode *p;
for (i = 0; i < G->n; i++)
G->adjlist[i].count = 0;
for (i = 0; i < G->n; i++)
{
p = G->adjlist[i].firstarc;
while (p != NULL) {
G->adjlist[p->adjvex].count++;
p = p->nextarc;
}
}
for (i = 0; i < G->n; i++)
if (G->adjlist[i].count == 0)
{
top++;
St[top] = i;
}
while (top > -1)
{
i = St[top];
top--;
printf("%d ", i);
p = G->adjlist[i].firstarc;
while (p != NULL) {
j = p->adjvex;
G->adjlist[j].count--;
if (G->adjlist[j].count == 0)
{
top++;
St[top] = j;
}
p = p->nextarc;
}
}
}
int main()
{
int i, j;
MGraph g;
ALGraph *G;
g.n = 6;
g.e = 6;
int A[MAXV][MAXV] = {
{0, 0, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 0},
{0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0}
};
for (i = 0; i < g.n; i++)
for (j = 0; j < g.n; j++)
g.edges[i][j] = A[i][j];
MatToList(g, G);
DispAdj(G);
printf("\n");
printf("拓扑序列:");
TopSort(G);
printf("\n");
}