fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // A structure to represent an adjacency list node
  5. struct AdjListNode
  6. {
  7. int dest;
  8. struct AdjListNode* next;
  9. };
  10.  
  11. // A structure to represent an adjacency liat
  12. struct AdjList
  13. {
  14. struct AdjListNode *head; // pointer to head node of list
  15. };
  16.  
  17. // A structure to represent a graph. A graph is an array of adjacency lists.
  18. // Size of array will be V (number of vertices in graph)
  19. struct Graph
  20. {
  21. int V;
  22. struct AdjList* array;
  23. };
  24.  
  25. // A utility function to create a new adjacency list node
  26. struct AdjListNode* newAdjListNode(int dest)
  27. {
  28. struct AdjListNode* newNode =
  29. (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
  30. newNode->dest = dest;
  31. newNode->next = NULL;
  32. return newNode;
  33. }
  34.  
  35. // A utility function that creates a graph of V vertices
  36. struct Graph createGraph(int V)
  37. {
  38. struct Graph graph;
  39. struct AdjList* adlist = (struct AdjList*)malloc(V * sizeof(struct AdjList));
  40. int i;
  41. for(i=0;i<V;i++)
  42. adlist[i].head = NULL;
  43.  
  44. graph.array = adlist;
  45. graph.V = V;
  46.  
  47.  
  48. return graph;
  49. }
  50.  
  51. // Adds an edge to an undirected graph
  52. void addEdge(struct Graph graph, int src, int dest)
  53. {
  54. struct AdjListNode * node = newAdjListNode(dest);
  55. node ->next = graph.array[src].head;
  56. graph.array[src].head = node;
  57.  
  58. node = newAdjListNode(src);
  59. node ->next = graph.array[dest].head;
  60. graph.array[dest].head = node;
  61. }
  62.  
  63. // A utility function to print the adjacenncy list representation of graph
  64. void printGraph(struct Graph graph)
  65. {
  66. int v;
  67. for (v = 0; v < graph.V; ++v)
  68. {
  69. struct AdjListNode* pCrawl = graph.array[v].head;
  70. printf("\n Adjacency list of vertex %d\n head ", v);
  71. while (pCrawl)
  72. {
  73. printf("-> %d", pCrawl->dest);
  74. pCrawl = pCrawl->next;
  75. }
  76. printf("\n");
  77. }
  78. }
  79.  
  80. // Driver program to test above functions
  81. int main()
  82. {
  83. // create the graph given in above fugure
  84. int V = 5;
  85. struct Graph graph = createGraph(V);
  86. addEdge(graph, 0, 1);
  87. addEdge(graph, 0, 4);
  88. addEdge(graph, 1, 2);
  89. addEdge(graph, 1, 3);
  90. addEdge(graph, 1, 4);
  91. addEdge(graph, 2, 3);
  92. addEdge(graph, 3, 4);
  93.  
  94. // print the adjacency list representation of the above graph
  95. printGraph(graph);
  96.  
  97. return 0;
  98. }
Success #stdin #stdout 0s 2380KB
stdin
Standard input is empty
stdout
 Adjacency list of vertex 0
 head -> 4-> 1

 Adjacency list of vertex 1
 head -> 4-> 3-> 2-> 0

 Adjacency list of vertex 2
 head -> 3-> 1

 Adjacency list of vertex 3
 head -> 4-> 2-> 1

 Adjacency list of vertex 4
 head -> 3-> 1-> 0