数据结构拓扑排序C语言有c++

#include <iostream>

using namespace std;
#include<stdio.h>
#include<stdlib.h>
#define MVNum 100
#define OK 1
#define ERROR 0
int indegree[100];
int d[100];      //定义拓扑排序数组
typedef struct edge
{
    int adjvex;
    struct edge*nextarc;
}edge;
typedef struct graph
{
    char data;
    edge*firstarc;
}graph,graphlist[100];
typedef struct graphadj{
    int numvex,numarc;
    graphlist adjlist;
}graphadj;
void creategraph(graphadj*g);
void printfgraph(graphadj*g);
void find(graphadj*g,int indegree[]);
void toposort(graphadj*g);
int main()
{
    graphadj*g;
    g=(graphadj*)malloc(sizeof(graphadj));
    creategraph(g);
    printfgraph(g);
    toposort(g);
}
void find(graphadj*g,int indegree[])
{
    for(int i=0;i<g->numvex;i++)
    {
        indegree[i]=0;
    }
    for(int i=0;i<g->numvex;i++)
    {
        edge*p;
        p=g->adjlist[i].firstarc;
        while(p)
        {
            indegree[p->adjvex]++;
            p=p->nextarc;
        }
    }
}
void toposort(graphadj*g)
{
    find(g,indegree);
    int stack[100];
    int top=-1;
    for(int i=0;i<g->numvex;i++)
    {
        if(indegree[i]==0)
        {
            stack[++top]=i;
        }
    }
    int count=0;
    while(top!=-1)
    {
        int index;
        index=stack[top--];
        cout<<g->adjlist[index].data;
        ++count;
        edge *p;
        for(p=g->adjlist[index].firstarc;p;p=p->nextarc)
        {
            int k=p->adjvex;
            indegree[k]--;
            if(indegree[k]==0)
            {
                stack[++top]=k;
            }

        }
    }
    if(count<g->numvex)
    {
        cout<<"该图有回路";
        return;
    }
}
void creategraph(graphadj*g)
{
    edge*p;
    int i;
    int vi,vj;
    cout<<"请输入图的顶点树和边数:"<<endl;
    cin>>g->numvex>>g->numarc;
    for(i=0;i<g->numvex;i++)
    {
        cin>>g->adjlist[i].data;
    }
    for(i=0;i<g->numvex;i++)
    {
        g->adjlist[i].firstarc=NULL;
    }
    for(i=0;i<g->numarc;i++)
    {
        cout<<"请输入vi,vj边的顶点"<<endl;
        cin>>vi>>vj;

        p=(edge*)malloc(sizeof(edge));
        p->adjvex=vj;
        p->nextarc=g->adjlist[vi].firstarc;
        g->adjlist[vi].firstarc=p;
    }
}
void printfgraph(graphadj*g)
{
    int i,j,k;
    edge *p;
    cout<<"以下为邻接表的输出:"<<endl;
    for(i=0;i<g->numvex;i++)
    {
        cout<<g->adjlist[i].data<<" ";
        p=g->adjlist[i].firstarc;
        while(p)
        {
            cout<<p->adjvex<<" ";
            p=p->nextarc;
        }
        cout<<endl;
    }
}

可直接测试

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木火火木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值