-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.c
70 lines (51 loc) · 1.36 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
#include<stdio.h>
#include<stdlib.h>
struct node{
int vertex;
struct node *next;
};
struct Graph{
int numVertices;
struct node **adjLists;
};
struct node* createNode(int vertex){
struct node *newNode = malloc(sizeof(struct node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices){
int i;
struct Graph *graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
for(i = 0 ; i < vertices ; i++){
graph->adjLists[i] = NULL;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest){
struct node *newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void printGraph(struct Graph *g){
for(int i = 0 ; i < g->numVertices ; i++){
printf("%d -->", i);
while(g->adjLists[i]){
printf("%d ", g->adjLists[i]->vertex);
g->adjLists[i] = g->adjLists[i]->next;
}
printf("\n");
}
}
int main(){
struct Graph *myGraph = createGraph(10);
addEdge(myGraph, 3, 4);
addEdge(myGraph, 0, 2);
printGraph(myGraph);
return 0;
}