#include<iostream>
#include<stdio.h>
using namespace std;
#include<malloc.h>
#include<string.h>
#define MAX_NAME 5
#define MAX_VERTEX_NUM 20
#define OK 1
#define FALSE -1
typedef char VertexType[MAX_NAME];
typedef int InfoType;
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 king;
}ALGraph;
int LocateVex(ALGraph &G, VertexType &u)
{
for(int i = 0; i < G.vexnum; ++i)
if(strcmp(G.vertices[i].data,u) == 0)
return i;
return FALSE;
}
int CreateDG(ALGraph &G)
{
int IncInfo, i, j, k;
VertexType v1,v2;
cout << "请输入有向图的顶点数:" << endl;
cin >> G.vexnum;
cout << "请输入有向图的弧数:" << endl;
cin >> G.arcnum;
cout << "请输入有向图的弧是否含有其它信息:(有:1 无:0)" << endl;
cin >> IncInfo;
cout << "请输入有向图的所有顶点:" << endl;
for (i = 0; i < G.vexnum; ++i)
{
cout << "请输入第" << i+1 << "个顶点" << endl;
scanf("%s",&G.vertices[i].data);
G.vertices[i].firstarc = NULL;
}
cout << "请输入弧,如:(v1->v2)" << endl;
for (k = 0; k < G.arcnum; ++k)
{
cout << "请输入第" << k+1 << "条弧" << endl;
cin >> v1;
cout << v1 << "->";
cin >> v2;
i = LocateVex(G,v1);
j = LocateVex(G,v2);
ArcNode *p;
p = (ArcNode *)malloc(sizeof(ArcNode));
if(!p)
{
cout << "溢出" << endl;
return 0;
}
p->adjvex = j;
p->info = NULL;
p->nextarc = G.vertices[i].firstarc;
G.vertices[i].firstarc = p;
if(IncInfo)
{
cout << "请输入单链表的其它信息:" << endl;
cin >> *(p->info);
}
}
return OK;
}
void DisplayDG(ALGraph &G)
{
cout << "邻接表:" << endl;
for(int i = 0; i < G.vexnum; ++i)
{
cout << G.vertices[i].data << ' ';
for(ArcNode *p = G.vertices[i].firstarc; p!=NULL; p=p->nextarc)
{
cout << p->adjvex << ' ';
}
cout << endl;
}
}
void DestroyDG(ALGraph &G)
{
ArcNode *q;
for(int i = 0; i < G.vexnum; ++i)
for (ArcNode *p = G.vertices[i].firstarc; p!=NULL; )
{
q = p;
p = p->nextarc;
free(q);
cout<<"销毁图!"<<endl;
}
}
void du(ALGraph G) {
int a[G.vexnum];
int b[G.vexnum];
for(int i=0;i<G.vexnum;i++){
a[i]=0;
b[i]=0;
}
for(int i=0;i<G.vexnum;i++){
ArcNode *p=G.vertices[i].firstarc;
while(p!=NULL){
a[i]++;
p=p->nextarc;
}
cout<<G.vertices[i].data<<"的出度为:"<<a[i]<<endl;
}
for(int i=0;i<G.vexnum;i++){
ArcNode *p=G.vertices[i].firstarc;
while(p!=NULL) {
int k=p->adjvex;
b[k]++;
p=p->nextarc;
}
}
for(int i=0;i<G.vexnum;i++){
cout<<G.vertices[i].data<<"的入度为:"<<b[i]<<endl;
}
}
int main()
{
ALGraph G;
CreateDG(G);
DisplayDG(G);
DestroyDG(G);
du(G);
return 0;
}