Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6.     int vertex;
  7.     struct node* next;
  8. };
  9. struct node* createNode(int);
  10. struct Graph
  11. {
  12.     int numVertices;
  13.     struct node** adjLists;
  14. };
  15. struct Graph* createGraph(int vertices);
  16. void addEdge(struct Graph* graph, int src, int dest);
  17. void printGraph(struct Graph* graph);
  18. int main()
  19. {
  20.     struct Graph* graph = createGraph(6);
  21.     addEdge(graph, 0, 1);
  22.     addEdge(graph, 0, 2);
  23.     addEdge(graph, 1, 2);
  24.     addEdge(graph, 5, 1);
  25.     addEdge(graph, 1, 4);
  26.     addEdge(graph, 1, 3);
  27.     addEdge(graph, 2, 4);
  28.     addEdge(graph, 3, 4);
  29.     addEdge(graph, 4, 6);
  30.     addEdge(graph, 5, 1);
  31.     addEdge(graph, 5, 6);
  32.  
  33.     printGraph(graph);
  34.  
  35.     return 0;
  36. }
  37.  
  38.  
  39. struct node* createNode(int v)
  40. {
  41.     struct node* newNode = malloc(sizeof(struct node));
  42.     newNode->vertex = v;
  43.     newNode->next = NULL;
  44.     return newNode;
  45. }
  46.  
  47. struct Graph* createGraph(int vertices)
  48. {
  49.     struct Graph* graph = malloc(sizeof(struct Graph));
  50.     graph->numVertices = vertices;
  51.  
  52.     graph->adjLists = malloc(vertices * sizeof(struct node*));
  53.  
  54.     int i;
  55.     for (i = 0; i < vertices; i++)
  56.         graph->adjLists[i] = NULL;
  57.  
  58.     return graph;
  59. }
  60.  
  61. void addEdge(struct Graph* graph, int src, int dest)
  62. {
  63.     // Add edge from src to dest
  64.     struct node* newNode = createNode(dest);
  65.     newNode->next = graph->adjLists[src];
  66.     graph->adjLists[src] = newNode;
  67.  
  68.     // Add edge from dest to src
  69.     newNode = createNode(src);
  70.     newNode->next = graph->adjLists[dest];
  71.     graph->adjLists[dest] = newNode;
  72. }
  73.  
  74. void printGraph(struct Graph* graph)
  75. {
  76.     int v;
  77.     for (v = 0; v < graph->numVertices; v++)
  78.     {
  79.         struct node* temp = graph->adjLists[v];
  80.         printf("\n Adjacency list of vertex %d\n ", v);
  81.         while (temp)
  82.         {
  83.             printf("%d -> ", temp->vertex);
  84.             temp = temp->next;
  85.         }
  86.         printf("\n");
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement