-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.c
78 lines (72 loc) · 1.56 KB
/
graph.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "graph.h"
#include <stdlib.h>
bool edge_list_contains(edge_t *edge, node_t *target)
{
if (edge == NULL)
return false;
else if (edge->target == target)
return true;
else
return edge_list_contains(edge->next, target);
}
bool edge_list_add( edge_t** edge, node_t* target )
{
if( target == NULL || edge == NULL )
{
return false;
}
else if( *edge == NULL )
{
edge_t* new_edge = ( edge_t* ) malloc( sizeof( edge_t ) );
new_edge->target = target;
new_edge->next = NULL;
*edge = new_edge;
return true;
}
else
{
return edge_list_add( &( ( *edge )->next ), target );
}
}
void graph_init( graph_t* graph, int num_nodes )
{
graph->num_nodes = num_nodes;
graph->nodes = ( node_t* ) malloc( sizeof( node_t ) * num_nodes );
int i;
for( i = 0; i < num_nodes; ++i )
{
graph->nodes[i].value = i;
graph->nodes[i].edge_list = NULL;
}
}
void graph_fprint( FILE* stream, graph_t* graph )
{
fprintf( stream, "graph g {\n\tnode [shape=\"point\"];\n" );
int i;
for( i = 0; i < graph->num_nodes; ++i )
{
edge_t* current = graph->nodes[i].edge_list;
while( current )
{
// Only print edges in one direction
if (current->target <= &(graph->nodes[i]))
fprintf( stream, "\t%d -- %d;\n", graph->nodes[i].value, current->target->value );
current = current->next;
}
}
fprintf( stream, "}\n" );
}
void graph_destory(graph_t* graph)
{
for(int i =0; i < graph->num_nodes; i++)
{
edge_t* edge = graph->nodes[i].edge_list;
while(edge != NULL)
{
edge_t* temp_edge = edge->next;
free(edge);
edge = temp_edge;
}
}
free(graph->nodes);
}