I am trying to delete the multiple occurring edges in a graph. Each vertex in the graph can have multiple outgoing edges to the same destination. like this one (this is the adjacency list). For example there are 2 connection from (3 --> 2). The numbers in the parenthesis are showing the distance, cost and time for each edge. In this case, I want to delete all the edges that have longer times. for example the first line second connection, which takes 45 hours.
### 3 -> 2 (50-300-40) ---> 2 (55-450-45) ---> 4 (45-450-45) ---> 4 (75-600-60) ---> 1 (40-450-40) ---> 1 (85-750-90) ---> NULL
### 2 -> 1 (50-450-45) ---> 3 (45-300-30) ---> 4 (80-700-80) ---> NULL
### 4 -> 2 (55-535-60) ---> 3 (75-545-65) ---> 4 (20-200-20) ---> NULL
void delete_edge(graph *g, int source_no, int dest_no) {
// Find the source vertex
node *source_vertex = &g->heads[source_no];
list_node *current = source_vertex->head;
list_node *prev = NULL;
// Create a new adjacency list
list_node *new_head = NULL;
list_node *new_tail = NULL;
// Traverse the adjacency list of the source vertex
while (current != NULL) {
if (current->index_of_item == dest_no) {
// Found the edge to delete, skip it
list_node *temp = current;
current = current->next;
free(temp);
if (prev != NULL) {
prev->next = current;
} else {
source_vertex->head = current;
}
} else {
// Add the current edge to the new adjacency list
if (new_head == NULL) {
new_head = current;
new_tail = current;
} else {
new_tail->next = current;
new_tail = current;
}
prev = current;
current = current->next;
}
}
// Set the next pointer of the new tail to NULL
if (new_tail != NULL) {
new_tail->next = NULL;
}
}
void bfs_delte_version(graph *g) {
// Initialize the color of all vertices as White
for (int i = 0; i < g->number_of_vertices; i++) {
g->heads[i].color = White;
}
// Start BFS from the first node (source)
node *source = &g->heads[0];
source->color = Gray;
queue *q = make_queue();
enqueue(q, source);
while (!is_empty_queue(q)) {
queue_node *u = dequeue(q);
list_node *temp = u->n->head;
while (temp != NULL) {
if (g->heads[temp->index_of_item].color == White) {
g->heads[temp->index_of_item].color = Gray;
enqueue(q, &g->heads[temp->index_of_item]);
} else {
// Delete multiple occurring edges
delete_edge(g, u->n->data, temp->index_of_item);
}
temp = temp->next;
}
u->n->color = Black;
printf("%d\n", u->n->data);
}
}
I have changed my strategy to traverse the graph using BFS and then delete the edges, but I cannot figure out why it doesn't work. When called on a single edge, it doesn't change the graph, and when called on BFS traversal I get segmentation fault. I will appreciate your help