Wisdom Materials
Home
About Us
Our Clients
Careers
Services
Education
Jobs
News
Business
Health
Astrology
Entertainment
RealEstate
Devotion
Contact Us
Data Structures using C Language
/ Representation Of Graph c program
Program
Copy text
// Adjascency List representation in C #include
#include
struct node { int vertex; struct node* next; }; struct node* createNode(int); struct Graph { int Verticescount; struct node** adjacentlist; }; struct node* createNode(int v) { struct node* newNode = malloc(sizeof(struct node)); newNode->vertex = v; newNode->next = NULL; return newNode; } struct Graph* createAGraph(int vertices) { struct Graph* graph = malloc(sizeof(struct Graph)); graph->Verticescount = vertices; graph->adjacentlist = malloc(vertices * sizeof(struct node*)); int i; for (i = 0; i < vertices; i++) graph->adjacentlist[i] = NULL; return graph; } void addEdge(struct Graph* graph, int s, int d) { struct node* newNode = createNode(d); newNode->next = graph->adjacentlist[s]; graph->adjacentlist[s] = newNode; // Add edge from destination to source newNode = createNode(s); newNode->next = graph->adjacentlist[d]; graph->adjacentlist[d] = newNode; } void DrawGraph(struct Graph* graph) { int v; for (v = 0; v < graph->Verticescount; v++) { struct node* temp = graph->adjacentlist[v]; printf("\n Vertex %d\n: ", v); while (temp) { printf("%d -> ", temp->vertex); temp = temp->next; } printf("\n"); } } int main() { struct Graph* graph = createAGraph(4); addEdge(graph, 0, 1); addEdge(graph, 0, 2); addEdge(graph, 0, 3); addEdge(graph, 1, 2); DrawGraph(graph); return 0; }
Output
Vertex 0: : 3 -> 2 -> 1 -> Vertex 1: : 2 -> 0 -> Vertex 2: : 1 -> 0 -> Vertex 3: : 0 ->
Home
Back