/* 无向图的邻接表法创建图的C代码实现 */ #include#include #include #define MaxSize 20 //图顶点的最大数量 typedef char VertexType; //全局变量,记录图的结点的数量 int VertexNum; //定义图顶点 typedef struct GraphNode { VertexType ver; struct GraphNode *next; }GraphNode; //用邻接表法创建图 void CreateGraph( GraphNode **g ) { VertexType ch; //用来接收顶点名称 int i = 0; GraphNode *p, *q; (*g) = (GraphNode *)malloc(sizeof(GraphNode)*MaxSize);//分配一个结构体数组 printf("请输入图的顶点:\n"); //存储图的顶点 scanf("%c", &ch); while( '\n' != ch ) { (*g)[i].ver = ch; (*g)[i].next = NULL; i++; scanf("%c", &ch); } VertexNum = i; //记录顶点数 for( i=0; i ver ); scanf("%c", &ch); while( '\n' != ch ) { p = (GraphNode *)malloc(sizeof(GraphNode)); p->ver = ch; q->next = p; q = p; q->next = NULL; scanf("%c", &ch); } } } //打印邻接表法创建的图 void PrintGraph( GraphNode *g ) { GraphNode *p; printf("图的顶点为:\n"); //打印顶点 for( int i=0; i ver); p = p->next; } printf("\n"); } } int main() { GraphNode *g; CreateGraph( &g ); PrintGraph( g ); return 0; }
测试的图:
测试结果