Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Adjacency List Implementation of Graph.
- #include<stdio.h>
- #include<stdlib.h>
- // Data Structure for each vertex
- typedef struct AdjNode{
- int node;
- struct AdjNode* next;
- }AdjNode;
- // Structure to hold the Adjacency List
- typedef struct AdjList{
- struct AdjNode* head;
- }AdjList;
- // Structure to represent the Graph
- typedef struct Graph{
- int v;
- AdjList* arr;
- }Graph;
- // Function to create a graph
- Graph* createGraph(int v){
- int i;
- Graph *graph = (Graph *)malloc(v*sizeof(AdjList));
- graph -> v = v;
- for(i = 0; i < v; i++)
- graph->arr[i].head = NULL;
- return graph;
- }
- // Function to add an edge from src to dest in the graph
- Graph* addEdge(Graph* graph, int src, int dest){
- AdjNode* newdest = (AdjNode*)malloc(sizeof(AdjNode));
- newdest->node = dest;
- newdest->next = graph->arr[src].head;
- graph->arr[src].head = newdest;
- AdjNode* newsrc = (AdjNode*)malloc(sizeof(AdjNode));
- newsrc->node = src;
- newsrc->next = graph->arr[dest].head;
- graph->arr[dest].head = newsrc;
- return graph;
- }
- void printGraph(Graph *graph){
- int i;
- for (i=0; i< graph->v; i++)
- {
- printf("Current = %d\n",i);
- AdjNode* iter = graph->arr[i].head;
- while(iter != NULL)
- { printf("%d ->", iter->node);
- iter = iter->next;
- }
- printf("\n");
- }
- }
- int main(){
- Graph *g;
- int vertices;
- printf("Enter the number of vertices:");
- scanf("%d",&vertices);
- printf("Input");
- g = createGraph(vertices);
- printf("Graph");
- g = addEdge(g,0,1);
- g = addEdge(g,1,2);
- g = addEdge(g,2,3);
- g = addEdge(g,3,4);
- g = addEdge(g,4,0);
- g = addEdge(g,1,3);
- g = addEdge(g,2,4);
- printGraph(g);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement