1. 定义 vertex 和 edge的数据结构:
struct edge;
struct vertex
{
int visited;
int value;
struct vertex *next;
struct edge * first_edge;
};
struct edge
{
struct vertex *end_point;
struct edge *next_edge;
};
struct Graph
{
struct vertex *first_vertex;
struct vertex *last_vertex;
};
2. 添加一个顶点的函数:
void AddVertex(struct Graph *graph, int vertexValue)
{
struct vertex **head = &(graph->first_vertex);
struct vertex **tail = &(graph->last_vertex);
struct vertex *pVertex = (struct vertex *)malloc(sizeof(struct vertex));
pVertex->visited = 0;
pVertex->value = vertexValue;
pVertex->next = NULL;
pVertex->first_edge = NULL;
if(*head == NULL)
{
*head = pVertex;
*tail = pVertex;
}
else
{
(*tail)->next = pVertex;
*tail = pVertex;
}
}
3. 根据顶点的索引找到对应的顶点:
struct vertex * FindVertex(struct Graph *graph, int value)
{
struct vertex *pVertex = graph->first_vertex;
while(pVertex)
{
if(pVertex->value == value)
{
return pVertex;
}
pVertex = pVertex->next;
}
return NULL;
}
4. 增加一条边:
void AddEdge(struct Graph *graph, int E1, int E2)
{
struct vertex *pV1 = FindVertex(graph, E1);
struct vertex *pV2 = FindVertex(graph, E2);
struct edge *pEdge = (struct edge *)malloc(sizeof(struct edge));
pEdge->end_point = pV2;
pEdge->next_edge = pV1->first_edge;
pV1->first_edge = pEdge;
pEdge = (struct edge *)malloc(sizeof(struct edge));
pEdge->end_point = pV1;
pEdge->next_edge = pV2->first_edge;
pV2->first_edge = pEdge;
}
5. 删除顶点和边:
void RemoveEdges(struct vertex * vertex)
{
struct edge *pEdge = vertex->first_edge;
while(pEdge)
{
struct edge *pTemp = pEdge;
pEdge = pEdge->next_edge;
free(pTemp);
}
}
void DestroyGraph(struct Graph *graph)
{
struct vertex *pVertex = graph->first_vertex;
while(pVertex)
{
RemoveEdges(pVertex);
struct vertex *pTemp = pVertex;
pVertex = pVertex->next;
free(pTemp);
}
}
6. DFS:
void DFS(struct Graph *graph, int vertex)
{
struct vertex *pVertex = FindVertex(graph, vertex);
if(pVertex->visited == 1)
{
return;
}
pVertex->visited = 1;
printf("%d ", vertex);
struct edge *pEdge = pVertex->first_edge;
while(pEdge && pEdge->end_point)
{
DFS(graph, pEdge->end_point->value);
pEdge = pEdge->next_edge;
}
}
7. 测试函数:
#define VERTEX_NUM 9
#define EDGE_NUM 10
int main(void)
{
struct Graph graph;
graph.first_vertex = graph.last_vertex = NULL;
int V = VERTEX_NUM;
int E = EDGE_NUM;
int edge[] ={1, 2, 1, 5, 1, 9, 2,3, 3, 4, 2, 5, 9, 6, 5, 6, 6, 7, 7, 8};
int i;
for(i = 0; i < V; i++)
{
AddVertex(&graph, i + 1);
}
for(i = 0; i < 2 * E; i += 2)
{
AddEdge(&graph, edge[i], edge[i + 1]);
}
DFS(&graph, 1);
printf("\n");
DestroyGraph(&graph);
return 0;
}
输出如下:
1 9 6 7 8 5 2 3 4