Advertisement
Guest User

Untitled

a guest
May 24th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. struct TList {
  5. int target;
  6. int peso;
  7. struct TList* next;
  8. };
  9.  
  10. typedef struct TList* List;
  11.  
  12. struct TGraph {
  13. List *adj;
  14. int nodes_count;
  15. };
  16.  
  17. typedef struct TGraph* Graph;
  18.  
  19. List appendNodeList(List L, int target);
  20. List initNodeList(int info);
  21. Graph initGraph(int nodes_count);
  22. void addEdge(Graph G, int source, int target);
  23. void printList(List L);
  24. void printGraph(Graph G);
  25. void printGraphAux(Graph G);
  26.  
  27. Graph initGraph(int nodes_count) {
  28. Graph G = (Graph)malloc(sizeof(struct TGraph));
  29. G->adj = (List *)calloc(nodes_count, sizeof(List));
  30. G->nodes_count = nodes_count;
  31. return G;
  32. }
  33.  
  34. void addEdge(Graph G, int source, int target) {
  35. assert(G != NULL);
  36. assert(source < G->nodes_count);
  37. assert(target < G->nodes_count);
  38. if (source != target) {
  39. G->adj[source] = appendNodeList(G->adj[source], target);
  40. }
  41.  
  42. }
  43.  
  44. List appendNodeList(List L, int target) {
  45. if (L != NULL) {
  46. if (L->target != target) {
  47. L->next = appendNodeList(L->next, target);
  48. }
  49. } else {
  50. L = initNodeList(target);
  51. }
  52. return L;
  53. }
  54.  
  55. List initNodeList(int info) {
  56. List L = (List)malloc(sizeof(struct TList));
  57. L->target = info;
  58. L->next = NULL;
  59. return L;
  60. }
  61.  
  62.  
  63. void printGraphAux(Graph G) {
  64. if (G != NULL) {
  65. int x = 0;
  66. for (x = 0; x < G->nodes_count; x++) {
  67. printf("%d -> ", x);
  68. printList(G->adj[x]);
  69. printf("\n");
  70. }
  71. }
  72. }
  73.  
  74. void printGraph(Graph G) {
  75. printGraphAux(G);
  76. printf("\n\n");
  77. }
  78.  
  79.  
  80. void printList(List L) {
  81. if (L != NULL) {
  82. printf(" %d(%d) ", L->target, L->peso);
  83. printList(L->next);
  84. }
  85. }
  86.  
  87.  
  88. int main()
  89. {
  90.  
  91. int n,e,i,v,u,l;
  92. struct TGraph *G;
  93.  
  94.  
  95. printf("\nEnter the number of vertices - ");
  96. scanf("%d",&n);
  97.  
  98. G = initGraph(n);
  99. printf("\nEnter the number of edges - ");
  100. scanf("%d",&e);
  101.  
  102. printf("\nVertices are - ");
  103. for(i=0;i<n;i++)
  104. printf("%d ",i);
  105.  
  106.  
  107. printf("\nEnter the edges separated by space - ");
  108. for(i=0;i<e;i++)
  109. {
  110. scanf("%d%d",&v,&u);
  111. addEdge(G,v,u);
  112. }
  113.  
  114. printGraph(n);
  115.  
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement