Monday 8 June 2015

C Program to implement graphs 

As we know that a graph is generally represented using two notations 
namely 1) Adjacency Matrix 2) Adjacency List 
The first representation is pretty much simple but later is important one.
The choice of using either representation depends upon the task you are performing with the graph.
When the graph is sparse (i.e having less no. of edges we uses Adjacency List as it consumes less space when there are less no of edges in a graph)

Here is the implementation of the same 
The graph used here is :










#include<stdio.h>
#include<stdlib.h>

struct node
{
    int a;
    struct node * next;
};
struct graph
{
    int v;
    struct node **array;
};
void addedge(struct graph *g,int s,int d)
{
    struct node*temp ;
    temp= (struct node *)malloc(sizeof(struct node));
    temp->a=d;
    temp->next=g->array[s];// adding the node at the starting of the list
    g->array[s]=temp;
}
void printgraph(struct graph *g)
{
    struct node *temp;
    int i;
    printf("Adjaceny List representation of the graph is \n ");
    for(i=0;i<g->v;i++)
    {
        temp = g->array[i];
        printf("%d->",i);
        while(temp)
        {
            printf("%d->",temp->a);
            temp=temp->next;
        }
        printf("\n");
    }
}

int main()
{
struct graph *g;
g=(struct graph *)malloc(sizeof(struct graph));
g->v=5;
g->array=(struct node **)malloc(5*sizeof(struct node*));
int i;
for(i=0;i<5;i++) //intializing the graph
{
    g->array[i]=NULL;
}
addedge(g,0,1);
addedge(g,0,4);
addedge(g,4,0);
addedge(g,4,1);
addedge(g,4,3);
addedge(g,3,4);
addedge(g,3,1);
addedge(g,3,2);
addedge(g,1,0);
addedge(g,1,2);
addedge(g,1,3);
addedge(g,1,4);
addedge(g,2,1);
addedge(g,2,3);
printgraph(g);

return 0;

}
Output:



2 comments:

  1. struct node **array: ///means
    it is a 2d array dynamic type or
    it stores the address of structre to node

    ReplyDelete
  2. @Digant Gupta ,.basically its a double pointer i.e a pointer to a pointer to struct node , yes it stores the address of the pointer to the struct node and hence it can also be used as an array to store the array of pointers to the type struct

    ReplyDelete