数据结构C语言-拓扑排序

#include <stdio.h>
#include <stdlib.h>

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int status;
typedef int ElemType;
typedef int bool;
#define true 1
#define false 0

#define MaxInt 32767
#define MVNum 100
typedef char VerTexType;
typedef int ArcType;

typedef int OtherInfo;

//邻接表
typedef struct ArcNode
{
int adjvex;
struct ArcNode *nextarc;
OtherInfo info;
}ArcNode;

typedef struct VNode
{
VerTexType data;
ArcNode *firstarc;
}VNode,AdjList[MVNum];

typedef struct
{
AdjList vertices;
int vexnum,arcnum;
}ALGraph;

int LocateVex_AL(ALGraph G,VerTexType v)
{
int i=0;
while(i<G.vexnum&&G.vertices[i].data!=v)
i++;
if(i>=G.vexnum)
return ERROR;
return i;
}

status CreateUDN_AL(ALGraph *G,VerTexType *V)
{
int i=0,k=0,j;
for(;i<(*G).vexnum;i++)//G->就完事了!
{
G->vertices[i].data=V[i];
G->vertices[i].firstarc=NULL;
}
char v1,v2;
for(;karcnum;k++)
{
scanf("%c %c",&v1,&v2);
getchar();
int i=LocateVex_AL(*G,v1);
int j=LocateVex_AL(*G,v2);
ArcNode *p1=(ArcNode )malloc(sizeof(ArcNode));
p1->adjvex=j;
p1->nextarc=G->vertices[i].firstarc;
G->vertices[i].firstarc=p1;
/

ArcNode *p2=(ArcNode *)malloc(sizeof(ArcNode));
p2->adjvex=i;
p2->nextarc=G->vertices[j].firstarc;
G->vertices[j].firstarc=p2;
*/
}
return OK;
}

//栈
#define MAXSIZE 100
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;

status InitStack(SqStack *s)
{
s->base=(ElemType *)malloc(sizeof(ElemType)*MAXSIZE);
if(!s->base)
exit(OVERFLOW);
s->top=s->base;
s->stacksize=MAXSIZE;
return OK;
}

status Push(SqStack *s,ElemType e)
{
if(s->top-s->base==s->stacksize)
return ERROR;
*(s->top)=e;
s->top++;
return OK;
}

status Pop(SqStack *s,ElemType *e)
{
if(s->top==s->base)
return ERROR;
s->top–;
e=(s->top);
return OK;
}

bool StackEmpty(SqStack s)
{
return s.top==s.base;
}

//拓扑排序
void FindInDegree(ALGraph G,int indegree[])
{
int i,d=0;
for(i=0;i<G.vexnum;i++)
indegree[i]=0;
for(i=0;i<G.vexnum;i++)
{
ArcNode *p=G.vertices[i].firstarc;
while(p!=NULL)
{
indegree[p->adjvex]++;
p=p->nextarc;
}
}
}

status TopologicalSort(ALGraph G,int topo[])
{
int indegree[G.vexnum],i;
FindInDegree(G,indegree);
SqStack S;
InitStack(&S);
for(i=0;i<G.vexnum;i++)
if(!indegree[i])
Push(&S,i);
int m=0;
while(!StackEmpty(S))
{
Pop(&S,&i);
topo[m]=i;
m++;
ArcNode *p=G.vertices[i].firstarc;
while(p!=NULL)
{
int k=p->adjvex;
indegree[k]–;
if(indegree[k]==0)
Push(&S,k);
p=p->nextarc;
}
}
if(m<G.vexnum)
return ERROR;
else
return OK;
}
int main()
{
ALGraph G;
G.vexnum=6;
G.arcnum=8;
VerTexType V[G.vexnum];
int i;
for(i=0;i<G.vexnum;i++)
V[i]=i+‘A’;
printf(“Create ALGraph:\n”);
CreateUDN_AL(&G,V);
int topo[G.vexnum];
printf(“Topo sort:\n”);
if(TopologicalSort(G,topo)>0)
{
for(i=0;i<G.vexnum;i++)
printf("%d ",topo[i]+1);
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值