#include <stdio.h>
#include <stdlib.h>
// Define a structure for an edge
typedef struct Edge {
char from;
char to;
int directed; // 1 if directed, 0 if undirected
int weight; // 0 if no weight
struct Edge* next;
} Edge;
// Define a structure for a graph
typedef struct Graph {
char vertices[10];
int vertex_count;
Edge* edges;
} Graph;
// Function to add an edge to the graph
void add_edge(Graph* g, char from, char to, int directed, int weight) {
Edge* new_edge = (Edge*)malloc(sizeof(Edge));
new_edge->from = from;
new_edge->to = to;
new_edge->directed = directed;
new_edge->weight = weight;
new_edge->next = g->edges;
g->edges = new_edge;
}
// Function to print the graph
void print_graph(Graph* g) {
printf("Vertices: ");
for (int i = 0; i < g->vertex_count; i++) {
printf("[%c] ", g->vertices[i]);
}
printf("\nEdges:\n");
Edge* current = g->edges;
while (current != NULL) {
if (current->directed) {
if (current->weight > 0) {
printf("%c -> %c (weight %d)\n", current->from, current->to, current->weight);
} else {
printf("%c -> %c\n", current->from, current->to);
}
} else {
if (current->weight > 0) {
printf("%c <-> %c (weight %d)\n", current->from, current->to, current->weight);
} else {
printf("%c <-> %c\n", current->from, current->to);
}
}
current = current->next;
}
}
int main() {
Graph g;
g.vertex_count = 4;
g.vertices[0] = 'A';
g.vertices[1] = 'B';
g.vertices[2] = 'C';
g.vertices[3] = 'D';
g.edges = NULL;
add_edge(&g, 'A', 'B', 1, 0); // directed edge A->B
add_edge(&g, 'B', 'C', 0, 0); // undirected edge B<->C
add_edge(&g, 'C', 'D', 1, 5); // directed weighted edge C->D weight 5
print_graph(&g);
return 0;
}Edge* new_edge = (Edge*)malloc(sizeof(Edge));
allocate memory for new edge
new_edge->from = from;
new_edge->to = to;
new_edge->directed = directed;
new_edge->weight = weight;
set edge properties: start, end, direction, weight
new_edge->next = g->edges;
g->edges = new_edge;
insert new edge at the front of edge list
while (current != NULL) { ... current = current->next; }
traverse all edges to print them
Vertices: [A] [B] [C] [D]
Edges:
C -> D (weight 5)
B <-> C
A -> B