拓扑排序(算法 非可执行程序)

 

假设有个有向图G已经从十字链表形式存储在内存中,试写一个判断该有向图是否有环(回路)的算法。

define MAX_VERTEX_NUM 20

typedef struct ArcBox{

   Int tailvex,headvex;

   Struct ArcBox *hlink,*tlink:

   InforType  info;

}ArcBox;//定义弧

 

tpedef struct vexnode{

VertexType data;

ArcBox *firstin,*firstout;

}VexNode;//定义定点

 

typedef struct{

 VexNode Xlist[MAX_VERTEX_NUM];

  Int vexnum arcnum;

}OLGraph;//定义图

 

LocatFirstNull(OLGraph &G, int i, int n)

//查找第一个没有前驱的顶点,即第一个firstin为空的顶点,返回其位置i,n为循环次数,等于初始时顶点的个数。

{

  for(k=0;k<n;k++)

{

  if(!G.XList[k].firstin)

   {i=k;return true;}

}

return false;

}

LocatFistinheadVex(OLGraph &G,int j,int v2,int n)

//查找firstin指向弧的headvex=v2的顶点,返回其位置j

{

  for(i=0;i<n;i++)

{if(*G.XList[i].firstin.headvex==v2)

{j=i;return true;}

}retrun false;

}

 

TopSort(OLGraph &G)

{

ArcBox *p1,*p2,*pt;

 int i,j,n;

 n=G.vexnum;

while(LocatFirstNull(G,i,n))

{

p1=G.XList[i].firstout;

free(G.XList[i]);//释放数据,保留位置,可以使用无效数据填充;因为若把位置删除,会使图的存储变乱。在释放前加printf G.XList[i].data,最后得到该图拓扑序列。

G.vexnum--;

while(p1)

{

  if(LocateFirstinheadvex(G,j,*p1.headvex,n))

   {

p2=G.XList[j].firstin;

while(*p2.hink.tailvex!=*p1.tailvex)

p2=p2.hlink;

p2.hlink=h1.hlink;//修改同尾链域的指针,使原来指向要删除弧的指针,指向下一个或空。

}

t=p1;p1.tlink;

free(t);//释放以删除顶点为尾的弧;

G.arcnum--;

}

}

if(G.vexnum==0) printf 此图没有回路!;

else printf 此图有回路;

}

posted @ 2005-12-02 17:29  火火  阅读(1119)  评论(2编辑  收藏  举报