1、鍵盤輸入數據,建立一個有向圖的鄰接表。
2、輸出該鄰接表。
3、在有向圖的鄰接表的基礎上計算各頂點的度,並輸出。
4、以有向圖的鄰接表爲基礎實現輸出它的拓撲排序序列。
5、採用鄰接表存儲實現有向圖的深度優先遞歸遍歷。
6、編寫一個主函數,調試上述算法。
#include <stdio.h>
#include <stdlib.h>
#define MAXVNUM 100 //頂點最大個數
#define VertexType int
typedef struct Node
{
int adjvex;
struct Node *nextarc;
int weight;
} ArcNode;
typedef struct
{
int degree,indegree;
VertexType data;
ArcNode *firstarc;
} VNode;
typedef struct
{
VNode vertices[MAXVNUM];
int vexnum,arcnum;//頂點的實際數,邊的實際數
} ALGraph;
void CreatAdjList(ALGraph *A)
{
int n,i;
scanf("%d",&n);
A->vexnum=n;
for(i=1; i<=n; i++)
{
A->vertices[i].data=i;
A->vertices[i].firstarc=NULL;
}
int a,b;
scanf("%d,%d",&a,&b);
ArcNode *p;
A->arcnum=0;
while(a!=0&&b!=0)
{
A->arcnum++;
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=b;
p->nextarc=A->vertices[a].firstarc;
A->vertices[a].firstarc=p;
scanf("%d,%d",&a,&b);
}
}
int visited[MAXVNUM];
void DFSTraverse(ALGraph A)
{
printf("圖的深度遍歷 ");
int v;
for(v=1; v<=A.vexnum; v++)
visited[v]=0;
for(v=1; v<=A.vexnum; v++)
{
if(!visited[v]) DFS(A,v);
}
}
VertexType GraphFirstAdj(ALGraph A,int v)
{
ArcNode *p=A.vertices[v].firstarc;
if(p==NULL)
return 0;
else
return p->adjvex;
}
VertexType GraphNextAdj(ALGraph A,int v,int w)
{
ArcNode *p=A.vertices[v].firstarc;
if(p==NULL) return 0;
else
{
while(p->adjvex!=w)
{
p=p->nextarc;
}
if(p->adjvex==w&&p->nextarc!=NULL)
return p->nextarc->adjvex;
else
return 0;
}
}
void DFS(ALGraph A,int v)
{
printf("%d ",A.vertices[v].data);
visited[v]=1;
VertexType w;
for(w=GraphFirstAdj(A,v); w; w=GraphNextAdj(A,v,w))
{
if(!visited[w]) DFS(A,w);
}
}
void print(ALGraph A)
{
int v;
ArcNode *p;
for(v=1; v<=A.vexnum; v++)
{
printf("%d ",v);
p=A.vertices[v].firstarc;
while(p!=NULL)
{
printf("%d ",p->adjvex);
p=p->nextarc;
}
printf("\n");
}
}
void degree(ALGraph *A)
{
int v;
ArcNode *p;
for(v=1; v<=A->vexnum; v++)
{
A->vertices[v].indegree=0;
A->vertices[v].degree=0;
}
for(v=1; v<=A->vexnum; v++)
{
p=A->vertices[v].firstarc;
while(p!=NULL)
{
A->vertices[v].degree++;
A->vertices[p->adjvex].indegree++;
p=p->nextarc;
}
}
for(v=1; v<=A->vexnum; v++)
{
printf("頂點 <%d> 入度 %d 出度 %d\n",v,A->vertices[v].indegree, A->vertices[v].degree);
}
}
void toposort(ALGraph A)
{
int top=0,k,v,stack[MAXVNUM];
for(v=1; v<=A.vexnum; v++)
if(A.vertices[v].indegree==0)
stack[top++]=v;
ArcNode *p;
printf("拓撲排序爲 ");
while(top!=0)
{
v=stack[--top];
printf("%d -> ",A.vertices[v].data);
p=A.vertices[v].firstarc;
while(p!=NULL)
{
k=p->adjvex;
A.vertices[k].indegree--;
if(A.vertices[k].indegree==0)
stack[top++]=k;
p=p->nextarc;
}
}
puts("");
}
int main()
{
ALGraph A;
CreatAdjList(&A);
printf("打印鄰接表\n");
print(A);
printf("計算出度入度\n");
degree(&A);
toposort(A);
DFSTraverse(A);
return 0;
}
/*
5
1,2
4,2
5,4
3,5
3,1
0,0
6
1,3
2,3
2,4
2,5
3,4
3,6
4,6
5,6
0,0
*/