Advertisement
Guest User

Untitled

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