该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include
#include
#include
typedef struct Node
{
int adjvex; //该弧所指向的顶点的位置
struct Node* next; //指向下一个条弧的指针
}ArcNode;
typedef struct Vertex
{
int indegree; //存放顶点的入度
ArcNode* first_arc; //指向第一条依附该顶点的弧的指针
}VNode;
int iarray; //用数组存储拓扑序列
typedef struct
{
int* base;
int* top;
}Stack;
Stack S; //用栈暂存所有入度为0的顶点
void InitStack(Stack* S)
{
S->base = (int*)malloc(10 * sizeof(int));
S->top = S->base;
}
void Push(Stack* S, int e)
{
*S->top++ = e;
}
void Pop(Stack* S, int* e)
{
*e = *--S->top;
}
void create_graph(VNode* vlist, int n) //用邻接表构造图
{
int i, position;
ArcNode* p, * q;
for (i = 0; i != n; ++i)
{
//为每个顶点建立单链表
vlist->first_arc = 0;
vlist->indegree = 0;
printf("输入%d号顶点的邻接点(以-1结束)\n",
i);
scanf_s("%d", &position);
while (position != -1)
{
q = (ArcNode
*)malloc(sizeof(ArcNode));
if (!q)
{
printf("内存分配失败");
return;
}
q->adjvex =
position;
q->next = 0;
if (0 ==
vlist->first_arc)
{
vlist->first_arc = q;
}
else
{
p->next = q;
}
p = q;
scanf_s("%d",&position);
}
}
}
void get_indegree(VNode* vlist, int n) //得到每个顶点的入度
{
int i;
ArcNode* p;
for (i = 0; i != n; ++i)
{
for (p = vlist->first_arc; p; p = p->next)
{
++vlist->indegree; //将i号顶点的每个邻接点入度加1
}
}
/* for (i =0; i != n; ++i)
{
printf("%d ", vlist.indegree);
}
*/
}
void topological_sort(VNode* vlist, int n) //对用邻接表存储的有向图进行拓扑排序
{
int i, ix = 0, count = 0, k;
ArcNode* p;
p = NULL;
InitStack(&S);
get_indegree(vlist, n);
//得到各个顶点的入度
for (i = 0; i != n; ++i)
{
if (0 == vlist->indegree)
{
Push(&S,
i); //入度为0的顶点入栈
}
}
while (S.base != S.top)
{
Pop(&S, &i);
//栈顶元素出栈并返回e799bee5baa6e79fa5e98193e59b9ee7ad9431333332613738值i
iarray = i; //用数组保存这个入度为0的顶点位置
++count;
for (p = vlist->first_arc; p; p = p->next)
//对i号顶点的每个邻接点的入度减1
{
k = p->adjvex;
if (0 ==
--vlist->indegree)
{
Push(&S, k);
//若入度减为0,则入栈
}
}
}
if (count != n)
{
pr