DS – Program to Create Graph

Structures creations representing Vetex and Edge:

struct Vertex
{
            int data, status;
            struct Vertex *next;
            struct Edge *adj;
};
 
struct Edge 
{
            struct Vertex *next;
            struct Edge *adj;
};

Variables required constructing the Graph:

struct Vertex *start,*p,*q;
struct Edge *l,*k;

Physical representation v/s Logical representation:

The internal representation of Graph structure:

void create()
{
            int data, flag=0;
            start = NULL;
            printf(“Enter nodes (0 to stop) : \n”);
            while(1)
            {
                        scanf(“%d”, &data);
                        if(data==0)
                                    break;
                       
                        p = (struct Vertex*)malloc(sizeof(struct Vertex));
                        p->data = data;
                        p->status = 0;
                        p->next = NULL;
                        p->adj = NULL ;
                       
                        if(flag==0){
                                    start = p;
                                    q = p;
                                    flag++;
                        }
                        else{
                                    q->link = p;
                                    q = p; 
                        }
            }
p = start;
            while(p != NULL)
            {
                        printf(“Enter links to %d : (0 to stop) :”, p->data);
                        flag=0;
                        while(1){
                                    scanf(“%d”, &data);
                                    if(data==0)
                                                break;
                                    k = (struct Edge*)malloc(sizeof(struct Edge));
                                    k->adj = NULL;
                                   
                                    if(flag==0){
                                                p->adj = k;
                                                l = k;
                                                flag++;
                                    }
                                    else{
                                                l->adj = k;
                                                l = k;   
                                    }
                                    q = start;
                                    while(q){
                                                if(q->data == data)
                                                {
                                                            k->next = q;   
                                                            break;
                                                }
                                                q=q->next;
                                    }
                        }
                        p=p->next;
            }
}

Scroll to Top