Advertisement
Guest User

Adjacency List Implementation

a guest
Oct 10th, 2015
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. // Adjacency List Implementation of Graph.
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4.  
  5. // Data Structure for each vertex
  6. typedef struct AdjNode{
  7.     int node;
  8.     struct AdjNode* next;
  9. }AdjNode;
  10.  
  11. // Structure to hold the Adjacency List
  12. typedef struct AdjList{
  13.     struct AdjNode* head;
  14. }AdjList;
  15.  
  16. // Structure to represent the Graph
  17. typedef struct Graph{
  18.     int v;
  19.     AdjList* arr;
  20. }Graph;
  21.  
  22. // Function to create a graph
  23. Graph* createGraph(int v){
  24.     int i;
  25.     Graph *graph = (Graph *)malloc(v*sizeof(AdjList));
  26.     graph -> v = v;
  27.     for(i = 0; i < v; i++)
  28.         graph->arr[i].head = NULL;
  29.     return graph;
  30. }
  31.  
  32. // Function to add an edge from src to dest in the graph
  33. Graph* addEdge(Graph* graph, int src, int dest){
  34.     AdjNode* newdest = (AdjNode*)malloc(sizeof(AdjNode));
  35.     newdest->node = dest;
  36.     newdest->next = graph->arr[src].head;
  37.     graph->arr[src].head = newdest;
  38.    
  39.     AdjNode* newsrc = (AdjNode*)malloc(sizeof(AdjNode));
  40.     newsrc->node = src;
  41.     newsrc->next = graph->arr[dest].head;
  42.     graph->arr[dest].head = newsrc;
  43.    
  44.     return graph;
  45. }
  46.  
  47. void printGraph(Graph *graph){
  48.     int i;
  49.     for (i=0; i< graph->v; i++)
  50.     {
  51.         printf("Current = %d\n",i);
  52.         AdjNode* iter = graph->arr[i].head;
  53.         while(iter != NULL)
  54.         {   printf("%d ->", iter->node);
  55.             iter = iter->next;
  56.         }
  57.         printf("\n");
  58.     }
  59. }
  60.  
  61. int main(){
  62.     Graph *g;
  63.     int vertices;
  64.     printf("Enter the number of vertices:");
  65.     scanf("%d",&vertices);
  66.     printf("Input");
  67.     g = createGraph(vertices);
  68.     printf("Graph");
  69.     g = addEdge(g,0,1);
  70.     g = addEdge(g,1,2);
  71.     g = addEdge(g,2,3);
  72.     g = addEdge(g,3,4);
  73.     g = addEdge(g,4,0);
  74.     g = addEdge(g,1,3);
  75.     g = addEdge(g,2,4);
  76.     printGraph(g);
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement