出边、入边使用同一顶点数组
注意输入顶点序号与数组下标的关系
#include <iostream>
#include <stdlib.h>
#define MAX 100
using namespace std;
//邻接表表示有向图
typedef struct ArcNode{//边节点
int index;
ArcNode *nextarc;
};
typedef struct VNode{//顶点节点
int index;
ArcNode *head1;//出边表头节点
ArcNode *head2;//入边表头节点
};
//图
typedef struct Graph{
VNode vertexs[MAX];
int vernum,edgenum;
};
Graph g;
//创建邻接表
void createGraph(){
cin>>g.vernum>>g.edgenum;
for(int i=0; i<g.vernum; i++){
g.vertexs[i].index = i;
g.vertexs[i].head1 = g.vertexs[i].head1 = NULL;
}
int invertex, outvertex;
ArcNode *arcnode;
while(cin>>invertex>>outvertex,invertex,outvertex){
//出边
arcnode = (ArcNode*)malloc(sizeof(ArcNode));
arcnode->index = outvertex;
arcnode->nextarc = g.vertexs[invertex-1].head1;
g.vertexs[invertex-1].head1 = arcnode;
//入边
arcnode = (ArcNode*)malloc(sizeof(ArcNode));
arcnode->index = invertex;
arcnode->nextarc = g.vertexs[outvertex-1].head2;
g.vertexs[outvertex-1].head2 = arcnode;
}
}
void indegree(){
int num;
for(int i=0; i<g.vernum; i++){
num=0;
ArcNode *arcnode = g.vertexs[i].head1;
while(arcnode){
num++;
arcnode = arcnode->nextarc;
}
if(i==0){
cout<<num;
}else{
cout<<" "<<num;
}
num=0;
}
cout<<endl;
}
void outdegree(){
int num;
for(int i=0; i<g.vernum; i++){
num=0;
ArcNode *arcnode = g.vertexs[i].head2;
while(arcnode){
num++;
arcnode = arcnode->nextarc;
}
if(i==0){
cout<<num;
}else{
cout<<" "<<num;
}
num=0;
}
cout<<endl;
}
/**
4 7
1 4
2 1
2 2
2 3
2 3
4 2
4 3
0 0
**/
int main()
{
createGraph();
indegree();
outdegree();
return 0;
}
1 4 0 2
1 2 3 1