Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "ListGraph.h"
- #include <stdio.h>
- #include <stdlib.h>
- void init_list_graph(ListGraph *graph, int nodes) {
- /* TODO */
- graph->nodes = nodes;
- graph->neighbors = (LinkedList **)malloc(nodes * sizeof(LinkedList *));
- if (graph->neighbors == NULL) {
- fprintf(stderr, "List not initialised.\n");
- return;
- }
- for (int i = 0; i < nodes; ++i) {
- graph->neighbors[i] = (LinkedList *)malloc(sizeof(LinkedList));
- if (graph->neighbors[i] == NULL) {
- fprintf(stderr, "List not initialised.\n");
- return;
- }
- init_list(graph->neighbors[i]);
- }
- }
- void add_edge_list_graph(ListGraph *graph, int src, int *dest) {
- /* TODO */
- add_nth_node(graph->neighbors[src], graph->neighbors[src]->size, dest);
- }
- int has_edge_list_graph(ListGraph *graph, int src, int dest) {
- /* TODO */
- struct Node *curr;
- int found = 0;
- if (graph->neighbors[src] == NULL) {
- fprintf(stderr, "List not initialised.\n");
- return 0;
- }
- if (graph->neighbors[src]->size == 0) {
- return 0;
- }
- curr = graph->neighbors[src]->head;
- while (curr->next != NULL) {
- if (*((int *)curr->data) == dest) {
- found = 1;
- break;
- }
- curr = curr->next;
- }
- if (found == 1) {
- curr = graph->neighbors[dest]->head;
- while (curr->next != NULL) {
- if (*((int *)curr->data) == src) {
- return 1;
- }
- curr = curr->next;
- }
- fprintf(stderr, "Graph is not undirected.\n");
- }
- return 0;
- }
- LinkedList *get_neighbours_list_graph(ListGraph *graph, int node) {
- /* TODO */
- if (graph->neighbors[node] == NULL) {
- fprintf(stderr, "List not initialised.\n");
- return NULL;
- }
- return graph->neighbors[node];
- }
- void remove_edge_list_graph(ListGraph *graph, int src, int dest) {
- /* TODO */
- struct Node *curr, *tmp;
- int found = 0;
- if (graph->neighbors[src] == NULL) {
- fprintf(stderr, "List not initialised.\n");
- return;
- }
- if (graph->neighbors[dest] == NULL) {
- fprintf(stderr, "List not initialised.\n");
- return;
- }
- curr = graph->neighbors[src]->head;
- for (int i = 0; i < graph->neighbors[src]->size; ++i) {
- if (*(int *)curr->data == dest) {
- tmp = remove_nth_node(graph->neighbors[src], i);
- free(tmp);
- found = 1;
- break;
- } else if (i == graph->neighbors[src]->size - 1) {
- fprintf(stderr, "Element not found.\n");
- return;
- }
- curr = curr->next;
- }
- if (found == 1) {
- curr = graph->neighbors[dest]->head;
- for (int i = 0; i < graph->neighbors[dest]->size; ++i) {
- if (*(int *)curr->data == src) {
- tmp = remove_nth_node(graph->neighbors[dest], i);
- free(tmp);
- return;
- } else if (i == graph->neighbors[src]->size - 1) {
- fprintf(stderr, "Graph is not undirected.\n");
- return;
- }
- curr = curr->next;
- }
- }
- }
- void clear_list_graph(ListGraph *graph) {
- /* TODO */
- for (int i = 0; i < graph->nodes; ++i) {
- free_list(&graph->neighbors[i]);
- }
- free(graph->neighbors);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement