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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <stdlib.h>

typedef struct Node Node;
typedef struct UndirectedGraph UndirectedGraph;

struct Node {
	int data;
	Node * next;
};

struct UndirectedGraph {
	int vertexes;
	Node ** head_refs;
};

void insert_right(Node ** head, int data) {
	Node * newNode = (Node *) malloc(sizeof(Node));
	newNode->data = data;
	newNode->next = NULL;

	if (*head == NULL) {
		*head = newNode;
	} else {
		Node * p = *head;
		while (p->next != NULL) {
			p = p->next;
		}

		p->next = newNode;
	}
}

void delete(Node ** head, int data) {
	if (*head == NULL) {
		printf("List is empty\n");
	} else {
		Node * p = *head;
		int index = 0;
		
		if (p->data == data) {
			*head = p->next;
      free(p);
		} else {
			while (p->next->data != data) {
				p = p->next;
				index++;
			}

			Node * q = p->next;
    	p->next = q->next;
    	free(q);
		}
	}
}

void print(Node ** head) {
	Node * p = *head;
	if (p == NULL) {
		printf(" -> NULL\n");
	} else {
		while (p != NULL) {
			printf(" -> %d", p->data);
			p = p->next;
		}
		printf("\n");
	}
}

UndirectedGraph * make_graph(int vertexes) {
	UndirectedGraph * graph = (UndirectedGraph *) malloc(sizeof(UndirectedGraph));

	graph->vertexes = vertexes; // storing the amount of vertexes
	graph->head_refs = (Node **) malloc(vertexes * sizeof(Node)); // make as many head references as the amount of vertexes

	// initialize every head reference to NULL
	int i;
	for (i = 0; i < vertexes; i++) {
		graph->head_refs[i] = NULL;
	}

	return graph;
}

void add_edge(UndirectedGraph * graph, int head, int vertex) {
	insert_right(&graph->head_refs[head], vertex);
	insert_right(&graph->head_refs[vertex], head);
}

void delete_edge(UndirectedGraph * graph, int head, int vertex) {
	delete(&graph->head_refs[head], vertex);
	delete(&graph->head_refs[vertex], head);
}

void print_graph(UndirectedGraph * graph) {
	int i;
	for (i = 0; i < graph->vertexes; i++) {
		printf("(head) %d", i);
		print(&graph->head_refs[i]);
	}
}

int main() {
	UndirectedGraph * graph = make_graph(3);

	/*
				0
			/		\
		1	---- 2
  */

	add_edge(graph, 0, 1);
  add_edge(graph, 0, 2);
  add_edge(graph, 1, 2);
  
	print_graph(graph);

	printf("deletion of edge from 0 to 1\n");
  delete_edge(graph, 0, 1);

  print_graph(graph);
}