图的邻接表结构图:
代码部分:
adj_list_graph.h
#ifndef _ADJ_LIST_GRAPH_H
#define _ADJ_LIST_GRAPH_H
#include <stdio.h>
#include <stdlib.h>
#define GRAPH_NODE_INF (-1)
#define GRAPH_ERR (-1)
#define GRAPH_SUCCESS 0
typedef char VertexType;
typedef struct _edge_node {
VertexType data;
int weight;
struct _edge_node *next;
}EdgeNode, *PEdgeNode;
typedef struct _vertex_node {
VertexType data;
PEdgeNode head;
}VertexNode, *PVertexNode;
typedef struct _adj_graph {
PVertexNode node;
int edgeSize;
int nodeSize;
}AdjGraph, *PAdjGraph;
/* 初始化一个无向图 */
PAdjGraph GraphInit();
#endif
adj_list_graph.c
#include "adj_list_graph.h"
PAdjGraph GraphInit()
{
PAdjGraph graph = (PAdjGraph)malloc(sizeof(AdjGraph));
if(graph == NULL) {
perror("graph malloc error.");
return (PAdjGraph)GRAPH_ERR;
}
printf("Please input the number of vertex nodes.\n");
scanf("%d", &graph->nodeSize);
printf("Please input the number of edges.\n");
scanf("%d", &graph->edgeSize);
graph->node = (PVertexNode)malloc(sizeof(VertexNode) * graph->nodeSize);
if(graph->node == NULL) {
perror("vertex node malloc error.");
return (PAdjGraph)GRAPH_ERR;
}
/* get the node info of graph */
for(int i=0; i<graph->nodeSize; i++) {
printf("Please input the info of Vertex node[%d].\n", i+1);
scanf("%c\n", &graph->node[i].data);
graph->node[i].head = NULL;
}
char ch;
while((ch=getchar()) != '\n');
int iValue, jValue, weight;
for(int i=0; i<graph->edgeSize; i++) {
printf("please input the edge[%d] by (i,j)\n", i+1);
scanf("%d,%d", &iValue, &jValue);
printf("i=%d,j=%d\n", iValue, jValue);
printf("Please input the weight of edge[%d].\n", i+1);
scanf("%d", &weight);
if(iValue<0 || iValue>=graph->nodeSize || jValue<0 || jValue>=graph->edgeSize || weight <= 0) {
perror("node info error.");
return (PAdjGraph)GRAPH_ERR;
}
PEdgeNode addNodeI = (PEdgeNode)malloc(sizeof(EdgeNode));
if(addNodeI == NULL) {
perror("addNodeI malloc error.");
return(PAdjGraph)GRAPH_ERR;
}
addNodeI->data = graph->node[iValue].data;
addNodeI->weight = weight;
addNodeI->next = graph->node[iValue].head;
graph->node[iValue].head = addNodeI;
PEdgeNode addNodeJ = (PEdgeNode)malloc(sizeof(EdgeNode));
if(addNodeJ == NULL) {
perror("addNodeJ malloc error.");
return (PAdjGraph)GRAPH_ERR;
}
addNodeJ->data = graph->node[jValue].data;
addNodeJ->weight = weight;
addNodeJ->next = graph->node[jValue].head;
graph->node[jValue].head = addNodeJ;
}
printf("graph init completed.\n");
return graph;
}
main.c
#include "adj_list_graph.c"
int main(void)
{
PAdjGraph myGraph = GraphInit();
return 0;
}