Ad
Monday, May 8, 2023
Adjacency list
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int vertex;
struct Node* next;
} Node;
typedef struct Alist {
Node* head;
} Alist;
typedef struct Graph {
int V;
Alist* array;
} Graph;
Node* newnode(int vertex) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->vertex = vertex;
new_node->next = NULL;
return new_node;
}
Graph* createGraph(int V) {
Graph* graph = (Graph*) malloc(sizeof(Graph));
graph->V = V;
graph->array = (Alist*) malloc(V * sizeof(Alist));
for (int i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
void addedge(Graph* graph, int src, int vertex) {
Node* new_node = newnode(vertex);
new_node->next = graph->array[src].head;
graph->array[src].head = new_node;
new_node = newnode(src);
new_node->next = graph->array[vertex].head;
graph->array[vertex].head = new_node;
}
void printGraph(Graph* graph) {
for (int v = 0; v < graph->V; ++v) {
Node* tmp = graph->array[v].head;
printf("Adjacency list of vertex %d\n head ", v);
while (tmp) {
printf("-> %d", tmp->vertex);
tmp = tmp->next;
}
printf("\n");
}
}
// main function
int main() {
int V, E, src, vertex;
printf("Enter the number of vertices: ");
scanf("%d", &V);
Graph* graph = createGraph(V);
printf("Enter the number of edges: ");
scanf("%d", &E);
printf("Enter the edges as space separated pairs of vertices (0-indexed):\n");
for (int i = 0; i < E; i++) {
scanf("%d %d", &src, &vertex);
addedge(graph, src, vertex);
}
printGraph(graph);
return 0;
}
About Abhishek Dhamdhere
Qna Library Is a Free Online Library of questions and answers where we want to provide all the solutions to problems that students are facing in their studies. Right now we are serving students from maharashtra state board by providing notes or exercise solutions for various academic subjects
No comments:
Post a Comment