(1)在有向图中选一个没有前驱的顶点且输出之
(2)从图中删除该顶点和所有以它为尾的弧
#include “stdafx.h”
#include “malloc.h”
#define MAX_VERTEX_NUM 20
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
#define OVERFLOW -1
typedef int InfoType;
typedef char VertexType;
typedef int Status;
int indegree[60];
//图的定义
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
InfoType *info;
}ArcNode;
typedef struct VNode{
VertexType data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;
//定义一下栈
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//初始化栈
Status InitStack(SqStack &S){
S.base=(SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S.base) return (OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
//入栈
Status Push(SqStack &S,SElemType e){
if(S.top-S.base>=S.stacksize){
S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base) return (OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}
//出栈
Status Pop(SqStack &S,SElemType &e){
if(S.top==S.base) return ERROR;
e=*–S.top;
return OK;
}
//判断栈是否为空
Status StackEmpty(SqStack S){
if(S.top==S.base)
return OK;
else
return ERROR;
}
int LocateVex(ALGraph G, VertexType v) {
int i ;
for(i=0;i<G.vexnum;++i){
if(v==G.vertices[i].data)
return i;
}
return OVERFLOW;
}
//创建一个有向图
Status CreateDG(ALGraph &G) { VertexType v1, v2; int i,k,j; ArcNode *p,*q;
printf(“请输入节点个数\n”);
scanf(“%d”, &G.vexnum);
printf(“请输入边个数\n”);
scanf(“%d”, &G.arcnum);
printf(“请输入节点元素\n”);
getchar();
for (i = 0; i < G.vexnum; ++i){
scanf(“%c”, &G.vertices[i].data);
getchar();
}
for (i = 0; i < G.vexnum; ++i)
G.vertices[i].firstarc = NULL;
for (k = 0; k < G.arcnum; ++k) {
printf(“请输入边\n”);
scanf(“%c”,%c, &v1,&v2);
getchar();
i = LocateVex(G, v1);
j = LocateVex(G, v2);
p = (ArcNode *)malloc(sizeof(ArcNode));
if (!G.vertices[i].firstarc)
G.vertices[i].firstarc = p;
else {
for (q = G.vertices[i].firstarc;q->nextarc;q = q->nextarc);
q->nextarc = p;
}
p->adjvex = j;
p->nextarc = NULL;
}
return OK;
}
Status FindInDegree(ALGraph G){
int k;
for(int i=0;i<G.vexnum;i++){
indegree[i]=0;
}
for(int i=0;i<G.vexnum;i++){
ArcNode *p=G.vertices[i].firstarc;
while(p)
{
indegree[p->adjvex]++;
p=p->nextarc;
}
}
return OK;
}
//拓扑排序
Status TopologicalSort(ALGraph G){
int i,k;
ArcNode *p;
SqStack S;
CreateDG(G);
FindInDegree(G);
InitStack(S);
for(i=0;i<G.vexnum;i++){
if(!indegree[i]) {
Push(S,i);
}
}
int count=0;
printf(“拓扑排序结果是:”);
while(!StackEmpty(S)){
Pop(S,i);
printf(“%c “,G.vertices[i].data);
count++;
for(p=G.vertices[i].firstarc;p;p=p->nextarc){
k=p->adjvex;
if(!(–indegree[k])) Push(S,k);
}
}
if(count<G.vexnum) return ERROR;
else return OK;
}
void main(){
ALGraph G;
TopologicalSort(G);
}