选择合适的结构表示图,在此基础上实现拓扑排序算法。
对所设计的图结构,提供必要的基本功能。
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 6
typedef struct Node
{
int vertex;
struct Node* next;
} Node;
typedef struct Graph
{
Node* adjList[MAX_VERTICES];
int numVertices;
} Graph;
Graph* createGraph(int vertices)
{
//给图创建空间
Graph* graph = (Graph*)malloc(sizeof(Graph));
//给图的顶点数
graph->numVertices = vertices;
//循环创建指向 Node型的指针 均赋值为NULL
for (int i = 0; i < vertices; i++)
{
graph->adjList[i] = NULL;
}
return graph;
}
void addEdge(Graph* graph, int src, int dest)
{
//创建新的结点
Node* newNode = (Node*)malloc(sizeof(Node));
//新的结点的值
newNode->vertex = dest;
//新的结点指向,刚开始创建指针的指向
newNode->next = graph->adjList[src];
//刚开始创建的指针,指向新的1结点
graph->adjList[src] = newNode;
}
void topologicalSort(Graph* graph)
{
//入度数组,把结点的入度都存进去
int inDegree[MAX_VERTICES] = {0};
//队列
int queue[MAX_VERTICES], front = 0, rear = 0;
// 计算每个节点的入度
for (int i = 0; i < graph->numVertices; i++)
{
//temp指向刚开始创建的指针
Node* temp = graph->adjList[i];
while (temp)
{
inDegree[temp->vertex]++;
temp = temp->next;
}
}
// 将入度为0的节点依次入队
for (int i = 0; i < graph->numVertices; i++)
{
if (inDegree[i] == 0)
{
queue[rear++]= i;
}
}
// 拓扑排序
//计数防止有环
int count = 0;
while (front < rear)
{
//存放队列的头部
int currentVertex = queue[front++];
//打印出度为0的结点
printf("%d ", currentVertex);
//打印就加++记录数量
count++;
//创建一个指针,指向结点4指向的结点
Node* temp = graph->adjList[currentVertex];
while (temp)
{
//把入度减1
inDegree[temp->vertex]--;
//入度为0加入队列中
if (inDegree[temp->vertex] == 0)
{
queue[rear++]=temp->vertex;
}
temp = temp->next;
}
}
// 检查是否存在环
if (count != graph->numVertices)
{
printf("\n图中存在环,无法进行拓扑排序。\n");
} else
{
printf("\n");
}
}
void freeGraph(Graph* graph)
{
for (int i = 0; i < graph->numVertices; i++)
{
Node* temp = graph->adjList[i];
while (temp)
{
Node* toFree = temp;
temp = temp->next;
free(toFree);
}
}
free(graph);
}
int main()
{
// 硬编码图的顶点和边
Graph* graph = createGraph(MAX_VERTICES);
// 添加边 (src, dest)
addEdge(graph, 5, 2);
addEdge(graph, 5, 0);
addEdge(graph, 4, 0);
addEdge(graph, 4, 1);
addEdge(graph, 2, 3);
addEdge(graph, 3, 1);
printf("拓扑排序结果:\n");
topologicalSort(graph);
freeGraph(graph);
return 0;
}