repl.it
@pankajyd/

Implementing graph

C

No description

fork
loading
Files
  • main.c
main.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
79
80
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct vertex{
	int v;
	int color;
	struct vertex *neighbour;
}vertex;

// typedef struct list{
// 	int v;
// 	struct list* next;
// }list;

void free_adjList(vertex* V, int nv){
    vertex* tmp;
    for(int i = 0; i < nv; i++){
        list* head = V[i].neighbour;
        while(head != NULL){
            tmp = head;
            head = head->next;
            free(tmp);
        }
    }
}

int main(){
	//For a single graph
	vertex* V;
	int v1, v2;
	int nv, ne; //Number of vertices and edges
	list *tmp;

	//
	scanf("%d", &nv);
	scanf("%d", &ne);

	vertex G[nv];
	V = G;
	
	for(int i = 0; i < nv; i++){
		V[i].v = i;
		V[i].color = 0;
		V[i].neighbour = NULL;
	}

	while(ne--){
		scanf("%d %d", &v1, &v2);
		list* ptr = (list*)malloc(sizeof(list));
		ptr->v = v2;

		if(V[v1].neighbour == NULL){
			V[v1].neighbour = ptr;
		}
		else{
			tmp = V[v1].neighbour;
			V[v1].neighbour = ptr;
			ptr->next = tmp;
		}
	}

	//Remove multiline comment below to print the graph.
	/*
	printf("\n");
	for(int i = 0; i < nv; i++){
		list* head = V[i].neighbour;
		printf("%d: ", i);
		while(head != NULL){
			printf("%d ", head->v);
			head = head->next;
		}
		printf("\n");
	}
	*/

	free_adjList(V, nv);
	return 0;
}