图 邻接链表的拓扑排序
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
相关文章推荐
- asp.net AdRotator控件
- mount命令详解
- 模块hashlib
- ubuntu 安装 右键终端 eclpse 远程终端
- Mysql常用函数
- Android程序报错,不能再console捕捉并定位到错误行,怎么办?
- 在源码环境中编译Android studio项目时的mk脚本编写
- LeetCode:Missing Number
- POJ2975(Nim游戏)
- PHP的常量
- 4种方法让SpringMVC接收多个对象
- 两种方式实现checkBox readonly功能
- C++第5次实验-数组分离
- 生产环境参数实例及分析【生产环境实例增加中】
- CTRL+SHIFT
- [置顶] iOS面试题积累和总结
- marquee标签实现页面内容的滚动效果
- 微信的平台搭建java http://blog.csdn.net/gebitan505/article/details/44595265
- 自定义控件——水波纹
- C语言深度解剖读书笔记