拓扑排序C语言

#include <stdio.h>
#include <stdlib.h>
#define n 6
#define SIZE 100
#define NEWSIZE 10
typedef struct arcnode
{
 int weight;
 int yu;
 struct arcnode *next;
} arcnode;
typedef struct node//头
{
 int rudu;//统计一下入度
 char info;
 struct arcnode *firstnext;
}node;
typedef int ElemType;
typedef struct
{
 ElemType *top;
 ElemType *base;
 int size;
}SqStack;
//chu shi hua 
int InitStack(SqStack &S)
{
 S.base=(ElemType*)malloc(sizeof(ElemType)*SIZE);
 if(!S.base) return 0;
 S.top=S.base;
 S.size=SIZE;
 return 1;
}
int Push(SqStack &S,ElemType e)
{
 if(S.top-S.base>=S.size)
 {
  S.base=(ElemType*)realloc(S.base,sizeof(ElemType)*(S.size+NEWSIZE));
  if(!S.base) return 0;
  S.top=S.base+S.size;
  S.size+=NEWSIZE;
 }
// *S.top++=e;
 *S.top=e;
 ++S.top;
 return 1;
}
int Pop(SqStack &S,ElemType &e)
{
 if(S.top==S.base) return 0;
 //e=*--S.top;
 --S.top;
 e=*S.top;
}
int isempty(SqStack &S)
{
 if(S.top==S.base) return 1;
 return 0;
}
int m;
void setTu(struct node Tu[])
{
int i,j,k,w;
 arcnode *p;
 printf("请输入是否有方向(0无 1有):");
 scanf("%d",&k);//0or1
 for(i=1;i<=n;i++)//初始化
 {
  Tu[i].rudu=0;//每个的入度的值为0
  Tu[i].firstnext=NULL;
 }
 printf("请输入边的集合:");
 scanf("%d%d%d",&i,&j,&w);//由i,->j, 权值
 while((i>=1)&&(i<=n)&&(j>=1)&&(j<=n))//当输入(0 0 0)跳出
 {
  p=Tu[i].firstnext;//把头的指向下一个的指针给p
  while(p!=NULL&&(p->yu!=j))//判断是否加过,防止重复
   p=p->next;
  if(p==NULL)
  {
   p=(arcnode*)malloc(sizeof(arcnode));
   p->yu=j;
   p->weight=w;
   p->next=Tu[i].firstnext;
   Tu[i].firstnext=p;
   ++(Tu[j].rudu);
  }
  if(k==0)
  {
   p=(arcnode*)malloc(sizeof(arcnode));
   p->yu=i;
   p->weight=w;
   p->next=Tu[j].firstnext;
   Tu[j].firstnext=p;
   ++(Tu[j].rudu);
  }
  printf("请输入i,j,w(若结束输入000)");
  scanf("%d%d%d",&i,&j,&w);
 }
} 
void tuopu(struct node Tu[])
{
 SqStack S;
 InitStack(S);
 Tu[1].info='a';
 Tu[2].info='b';
 Tu[3].info='c';
 Tu[4].info='d';
 Tu[5].info='e';
 Tu[6].info='f';
 int i,count;
 for(i=1;i<=n;i++)
 {
  if(Tu[i].rudu==0)
   Push(S,i);
 }
 count=0;
 int e;
  while(!isempty(S))
 {
 Pop(S,e); printf("%c",Tu[e].info);
  count++;
  arcnode *q;
  q=Tu[e].firstnext;
  while(q!=NULL)
  {
   int c;
   c=q->yu;
   Tu[c].rudu--;
   if(Tu[c].rudu==0)
    Push(S,c);
   q=q->next;
  } 
 }
 if(count<n)
 {
  printf("%d",count);
  printf("error");
 }
}
void main()
{
 struct node Tu[n+1];
 setTu(Tu);
 tuopu(Tu);
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值