Subscribe Us

Responsive Advertisement

Advertisement

graph by adjacency list

 

graph by adjacency list


#include<stdio.h>

#define size 4

struct node

{

    int data;

    struct node *next;

};

void graph(struct node * adj[],int numbernode)

{

    struct node *newnode;

    for(int i=0;i<numbernode;i++)

    {

        struct node *last=NULL;

        int num;

        printf("Enter total number of adjacency node : ");

        scanf("%d",&num);

        for(int j=0;j<num;j++)

        {

            int val;

            printf("enter neighbor : ");

            scanf("%d",&val);

            newnode=(struct node*)malloc(sizeof(struct node));

            newnode->data=val;

            newnode->next=NULL;

            if(adj[i]==NULL)

            {

                adj[i]=newnode;

            }

            else{

                last->next=newnode;

            }

            last=newnode;

        }

    }



}

void print(struct node * adj[],int numbernode)

{

    struct node *ptr=NULL;

    for(int i=0;i<numbernode;i++)

    {

        ptr=adj[i];

        while(ptr!=NULL)

        {

            printf("%d ",ptr->data);

            ptr=ptr->next;

        }

        printf("\n");

    }



}

int main()

{

    int node;

    printf("Enter number of node : ");

    scanf("%d",&node);

    struct node *head[node];

    for(int i=0;i<node;i++)head[i]=NULL;

    graph(head,node);

    print(head,node);

    return 0;

}


Post a Comment

0 Comments