1. /*
    2. 拓扑排序:
    3. 每次将入度为0的顶点输出,输出的同时将出边删除,直至所有顶点输出
    4. */
    5. #define _CRT_SECURE_NO_WARNINGS
    6. #define MAXSIZE 100
    7. typedef struct EdgeNode {//边表结点
    8. int index;//该边所指向的顶点的位置
    9. int weight;//权值
    10. EdgeNode *next;//下一个邻接边
    11. }EdgeNode;
    12. typedef struct VertexNode {//顶点表节点
    13. char info;//顶点信息
    14. EdgeNode *firstEdge;//指向第一条依附该顶点的边的指针
    15. }VertexNode, Adjlist[MAXSIZE];
    16. typedef struct {
    17. Adjlist adjlist;//顶点数组
    18. int numE, numV;//边数、顶点数
    19. }ALGraph;
    20. struct Stack
    21. {
    22. int* arr; //内存首地址
    23. int len; //栈的容量
    24. int top; //栈的下标
    25. };
    26. #include <stdio.h>
    27. #include <stdlib.h>
    28. void inDegree(ALGraph *G,int *indegree) {//统计每个顶点的入度,用数组保存
    29. int k;
    30. for (int i = 0; i < G->numV;i++) {
    31. k = 0;
    32. for (int j = 0; j < G->numV;j++) {
    33. /*if (i==j) {
    34. continue;
    35. }*/
    36. for (EdgeNode *p = G->adjlist[j].firstEdge; p;p=p->next) {
    37. if (p->index == i)
    38. indegree[i] = ++k;
    39. }
    40. }
    41. }
    42. }
    43. void topoSort(ALGraph *G) {
    44. Stack *s = (struct Stack*)malloc(sizeof(struct Stack));
    45. Stack *createStack(int );
    46. bool push(Stack *, int data);
    47. bool empty(Stack *);
    48. int top(Stack *);
    49. bool pop(Stack *);
    50. int *indegree = (int *)malloc(sizeof(int )*G->numV);
    51. for (int i = 0; i < G->numV;i++) {
    52. indegree[i] = 0;
    53. }
    54. int index;
    55. inDegree(G,indegree);
    56. s=createStack(G->numV);
    57. for (int i = 0; i < G->numV;i++) {//将入度为0的顶点入栈
    58. if (indegree[i]==0) {
    59. push(s,i);
    60. }
    61. }
    62. while (!empty(s)) {//栈不空,输出栈顶
    63. index = top(s);//查看栈顶元素
    64. printf("%c ", G->adjlist[index].info);//打印
    65. pop(s);//出栈
    66. for (EdgeNode *p = G->adjlist[index].firstEdge; p; p = p->next) {//将当前出栈的顶点所指向的顶点的入度均-1
    67. indegree[p->index]--;
    68. if (!indegree[p->index]) {//出现了入度为0,入栈
    69. push(s,p->index);
    70. }
    71. }
    72. }
    73. }
    74. int main() {
    75. ALGraph *G = (ALGraph *)malloc(sizeof(ALGraph *));
    76. void createGraphInFile(ALGraph *);
    77. void dispGraph(ALGraph *);
    78. createGraphInFile(G);//创建图
    79. dispGraph(G);
    80. topoSort(G);
    81. return 0;
    82. }