接着上一次的C++实现,这次用C语言写一遍。主要是多了栈Stack的实现部分。
参考了《数据结构》教材。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
//-----图的邻接表存储表示
#define MAX_VERTEX_NUM 20
typedef struct ArcNode{
int adjvex; //该弧所指向的顶点的位置
struct ArcNode *nextarc; //指向下一条弧的指针
ArcNode(){nextarc=0;}
}ArcNode;
typedef struct VNode{
int data; //顶点信息
ArcNode *firstarc; //指向第一条依附该顶点的弧的指针
VNode(){firstarc=0;}
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct{
AdjList vertices;
int vexnum,arcnum; //图的当前顶点数和弧数
}ALGraph;
//------ 栈的 顺序存储表示-------
#define STACK_INIT_SIZE 20 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量
typedef struct{
int *base; //始终指向栈底位置
int *top; //栈顶指针
int stacksize; //当前已分配的存储空间
bool InitStack();
int getTop();
bool pop();
bool empty();
bool push(int i);
}SqStack;
bool SqStack::InitStack() //构造一个空栈
{
base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!base)return false;
top = base;
stacksize = STACK_INIT_SIZE;
return true;
}
int SqStack::getTop() //若栈不空,返回栈顶元素
{
if(top==base)return -1;
return *(top-1);
}
bool SqStack::push(int i) //插入元素i为新的栈顶元素
{
if(top-base > stacksize){
base = (int *)realloc(base,(stacksize+STACKINCREMENT)*sizeof(int));
if(!base)return false;
top = base + stacksize;
stacksize += STACKINCREMENT;
}
*top = i;
top++;
return true;
}
bool SqStack::pop() //若栈不空,删除栈顶元素
{
if(top==base)return false;
top--;
return true;
}
bool SqStack::empty() //判断栈是否为空
{
return top==base;
}
bool TopologicalSort(ALGraph G,int *indegree)
{
int i,k;
SqStack s;
s.InitStack(); //建零入度顶点栈s
for(i=1;i<G.vexnum+1;i++)
{
if(!indegree[i]){s.push(i);} //入度为0者入栈
}
int count=0;
ArcNode *p;
while(!s.empty())
{
i = s.getTop();
s.pop();
printf("%d-->",G.vertices[i].data);
count++;
for(p=G.vertices[i].firstarc;p;p=p->nextarc)
{
k = p->adjvex;
indegree[k]--;
if(!indegree[k]){s.push(k);} //若入度减为0,则入栈
}
}
if(count<G.vexnum) return false; //该有向图有回路
return true;
}
int main()
{
int i;
ALGraph g;
FILE *fin;
fin = fopen("in.txt","r");
assert(fin != NULL);
printf("输入节点数和边数:");
fscanf(fin,"%d%d",&g.vexnum,&g.arcnum);
for(i=1;i<g.vexnum+1;i++)
g.vertices[i].data = i;
int b,e;
ArcNode *p;
int *indegree=(int *)malloc(sizeof(int)*(g.vexnum+1));
memset(indegree,0,sizeof(int)*(g.vexnum+1));
printf("逐一输入边的顶点对,形如 3 5 \n");
for(i=1;i<g.arcnum+1;i++)
{
printf("第%d条边:",i);
fscanf(fin,"%d%d",&b,&e);
p = new ArcNode();
p->adjvex = e;
p->nextarc = g.vertices[b].firstarc;
g.vertices[b].firstarc = p;
indegree[e]++;
printf("\n");
}
if(TopologicalSort(g,indegree))printf("正常完成!\n");
else printf("该有向图有回路!\n");
fclose(fin);
return 0;
}