-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.c
More file actions
100 lines (87 loc) · 2.4 KB
/
Copy pathgraph.c
File metadata and controls
100 lines (87 loc) · 2.4 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include "graph.h"
Node* createNode(int vertex) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;
}
Graph* createGraph(int vertices) {
Graph* graph = (Graph*) malloc(sizeof(Graph));
graph->vertices = vertices;
graph->adjLists = (Node**) calloc(vertices, sizeof(Node*));
return graph;
}
void addEdge_dir(Graph* graph, int src, int dest) {
// Create [dest] node, then push node at the head of list[src]
Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}
void removeEdge_dir(Graph* graph, int src, int dest) {
Node* temp = graph->adjLists[src];
Node* prev;
// if it's the head node, push list to the right
// else search dest node and delete it, connecting prev and next nodes
if(temp!=NULL && temp->vertex==dest) {
graph->adjLists[src] = temp->next;
}
else{
while(temp!=NULL && temp->vertex!=dest) {
prev = temp;
temp = temp->next;
}
if(temp) prev->next = temp->next;
}
free(temp);
}
void addEdge(Graph* graph, int src, int dest) {
addEdge_dir(graph, src, dest);
addEdge_dir(graph, dest, src);
}
void removeEdge(Graph* graph, int src, int dest) {
removeEdge_dir(graph, src, dest);
removeEdge_dir(graph, dest, src);
}
int nodeDegree(Graph* graph, int vertex) {
int deg=0;
Node* node = graph->adjLists[vertex];
while(node!=NULL) {
deg++;
node = node->next;
}
return deg;
}
int** toAdjMatrix(Graph* graph) {
int i;
int size = graph->vertices;
Node* temp;
int** adjMatrix = calloc(size, sizeof(int*));
for(i=0;i<size;i++) {
adjMatrix[i] = calloc(size, sizeof(int));
}
for(i=0;i<size;i++) {
temp = graph->adjLists[i];
while(temp) {
adjMatrix[i][temp->vertex]+=1;
temp = temp->next;
}
}
return adjMatrix;
}
void fprintGraph(FILE* fp, Graph* graph) {
int i;
for(i=0; i<graph->vertices; i++) {
Node* temp = graph->adjLists[i];
fprintf(fp, "\nAdjacency list of vertex %d\n", i);
while(temp) {
fprintf(fp, "%d -> ", temp->vertex);
temp = temp->next;
}
fprintf(fp, "\n");
}
}
void printGraph(Graph* graph) {
fprintGraph(stdout, graph);
}