图 邻接链表的拓扑排序

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值