您的位置:首页 > 其它

图 邻接链表的拓扑排序

2016-05-11 20:29 288 查看
#include<iostream>
#include<cstdio>
using namespace std;
#define MAX 10
typedef char Elemtype;
typedef struct link{
int num;
struct link *next;
}slink;
typedef struct{
struct{
Elemtype vertex;
slink *first;
int count;
}ve[MAX];
int vex,edge,tag;
}adjlist;
//创建邻接链表
void cregraph(adjlist *G,int n)
{
G->vex=n;
for(int i=0;i<n;i++)
{G->ve[i].vertex=i+'A';G->ve[i].first=NULL;G->ve[i].count=0;}
char x,y;
printf("Input edges(x-->y):");
scanf("%c%c",&x,&y);
G->ve[y-'A'].count++;
while(x!=' '&&y!=' ')
{
int t1=x-'A';
int t2=y-'A';
slink *s;
s=(slink *)malloc(sizeof(slink));
s->num=t2;
if(G->ve[t1].first==NULL)
{G->ve[t1].first=s;s->next=NULL;}
else{
slink *p,*q;
p=G->ve[t1].first;
if(p->num>s->num)
{s->next=p;G->ve[t1].first=s;}
else{
q=p->next;
while(q!=NULL&&q->num<s->num){p=q;q=p->next;}//q!=NULL这句话一定要写,判断q是否找到最后了,否则会内存泄漏
p->next=s;
s->next=q;
}
}
getchar();//防止读入空格回车
scanf("%c%c",&x,&y);
G->ve[y-'A'].count++;
}
}
//遍历邻接链表
void list(adjlist *G)
{
slink *p;
for(int i=0;i<G->vex;i++)
{
printf("%c:",i+'A');
p=G->ve[i].first;
while(p)
{
printf("%c",p->num+'A');
p=p->next;
}
printf("\n");
printf("count=%d\n",G->ve[i].count);
}
}
//拓扑排序
void topsort(adjlist *G)
{
int top=0;
slink *p;
char stack[MAX],ch,topgraph[MAX];
int cnt=0;
for(int i=0;i<G->vex;i++)
if(G->ve[i].count==0) stack[top++]=G->ve[i].vertex;
while(top)
{
ch=stack[--top];
topgraph[cnt++]=ch;
p=G->ve[ch-'A'].first;
while(p){
int t=p->num;
G->ve[t].count--;
if(!G->ve[t].count)
stack[top++]=G->ve[t].vertex;
p=p->next;
}
}
if(cnt<G->vex) printf("have circle\n");
else {printf("The topsort is:");for(int i=0;i<cnt;i++) printf("%c",topgraph[i]);printf("\n");}

}
int main()
{
adjlist *G;
int n;
scanf("%d",&n);
getchar();//防止读入空格回车
cregraph(G,n);
list(G);
topsort(G);
return 0;
}
//测试数据输入:AD AB AE BE BF CB CF EF ED
//输出:
//A:BDE
//count=0
//B:EF
//count=2
//C:BF
//count=0
//D:
//count=2
//E:DF
//count=2
//F:
//count=3
//The topsort is:CABEFD
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: