# include "ALGraph.h"
void InDegree2 ( ALGraph* G, const char * v)
{
int i, j;
int sum = 0 ;
i = get_ALpos ( G, v) ;
ArcNode* p;
for ( j = 0 ; j < G-> vexnum; j++ )
{
p = G-> vertex[ j] . nextarc;
while ( p != NULL )
{
if ( p-> index == i)
{
sum += p-> weight;
p = p-> next;
}
else
{
p = p-> next;
}
}
}
printf ( "\n%s的入度之和为%d" , v, sum) ;
}
void Allindegree2 ( ALGraph* G)
{
for ( int i = 0 ; i < G-> vexnum; i++ )
{
InDegree2 ( G, G-> vertex[ i] . data) ;
}
}
int main ( int argc, char * argv[ ] )
{
ALGraph* g;
CreateALGraph ( g) ;
PrintALGraph ( g) ;
Allindegree2 ( g) ;
DestroyALGraph ( g) ;
return 0 ;
}
头文件和其它函数
# pragma once
# include <stdio.h>
# include <stdlib.h>
# include <assert.h>
# include <stdbool.h>
# include <string.h>
# define MAX 100
typedef struct ArcNode
{
int index;
ArcNode* next;
int weight;
} ArcNode;
typedef struct Vnode
{
char data[ 20 ] ;
ArcNode* nextarc;
} VNode;
typedef struct
{
int arcnum;
int vexnum;
VNode vertex[ MAX] ;
} ALGraph;
ArcNode* Create_Arcnode ( int index, int weight) ;
void insert_arcnode ( ArcNode* * headnode, int index, int weight) ;
int get_ALpos ( ALGraph* G, const char * v) ;
void CreateALGraph ( ALGraph* & G) ;
void PrintALGraph ( ALGraph* G) ;
void DestroyALGraph ( ALGraph* G) ;
# include "ALGraph.h"
ArcNode* Create_Arcnode ( int index, int weight)
{
ArcNode* newnode = ( ArcNode* ) malloc ( sizeof ( ArcNode) ) ;
assert ( newnode) ;
newnode-> index = index;
newnode-> weight = weight;
return newnode;
}
void insert_arcnode ( ArcNode* * headnode, int index, int weight )
{
ArcNode* newnode = Create_Arcnode ( index, weight) ;
newnode-> next = * headnode;
* headnode = newnode;
}
int get_ALpos ( ALGraph* G, const char * v)
{
for ( int i = 0 ; i < G-> vexnum; i++ )
{
if ( strcmp ( G-> vertex[ i] . data, v) == 0 )
{
return i;
}
}
return - 1 ;
}
void CreateALGraph ( ALGraph* & G)
{
G = ( ALGraph* ) malloc ( sizeof ( ALGraph) ) ;
assert ( G) ;
printf ( "请输入边数和顶点数(用逗号间隔):" ) ;
scanf_s ( "%d,%d" , & G-> arcnum, & G-> vexnum) ;
printf ( "请输入顶点信息(用空格间隔):" ) ;
for ( int i = 0 ; i < G-> vexnum; i++ )
{
scanf_s ( "%s" , G-> vertex[ i] . data, 20 ) ;
G-> vertex[ i] . nextarc = NULL ;
}
char v1[ 20 ] = "" ;
char v2[ 20 ] = "" ;
int i, j, weight= 0 ;
for ( int k = 0 ; k < G-> arcnum; k++ )
{
printf ( "请输入第%d条边的起点和终点和权值(均用空格间隔):" , k + 1 ) ;
scanf_s ( "%s%s%d" , v1, 20 , v2, 20 , & weight) ;
i = get_ALpos ( G, v1) ;
j = get_ALpos ( G, v2) ;
if ( i == - 1 || j == - 1 )
{
printf ( "边的输入有误,请重新输入\n" ) ;
k-- ;
continue ;
}
insert_arcnode ( & G-> vertex[ i] . nextarc, j, weight) ;
}
}
# include "ALGraph.h"
void PrintALGraph ( ALGraph* G)
{
for ( int i = 0 ; i < G-> vexnum; i++ )
{
printf ( "%s:\t" , G-> vertex[ i] . data) ;
ArcNode* current = G-> vertex[ i] . nextarc;
while ( current != NULL )
{
int index = current-> index;
printf ( "%s(%d)\t" , G-> vertex[ index] . data, current-> weight) ;
current = current-> next;
}
printf ( "\n" ) ;
}
}
void DestroyALGraph ( ALGraph* G)
{
free ( G) ;
}