Advertisement
Guest User

Untitled

a guest
May 21st, 2020
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct edge{
  5. int key;
  6. struct edge *next;
  7. }edge;
  8.  
  9. typedef struct graph{
  10. int nv;
  11. edge **adj;
  12. }graph;
  13.  
  14. graph *inizializza_grafo(int n)
  15. {
  16. graph *G;
  17. int i;
  18.  
  19. G=(graph *) malloc (sizeof(graph));
  20. if (G==NULL)//controlla se la memoria è stata allocata
  21. printf("\nERRORE! Non è possibile allocare memoria\n");
  22. else
  23.  
  24. {
  25. G->adj=(edge**) malloc (n*sizeof(edge));
  26. if ((G->adj==NULL) && (n>0))//controlla se la memoria è stata allocata
  27. {
  28. printf("\nERRORE! Non è possibile allocare memoria\n");
  29. free(G);
  30. G=NULL;//annulla anche l'allocazione di sopra
  31. }
  32.  
  33. else
  34. {
  35. G->nv=n;
  36. for (i=0;i<n;i++)
  37. G->adj[i]=NULL;//tutti i vertici del grafo puntano a NULL
  38. }//end else
  39. }//end else
  40. return G;
  41. }
  42.  
  43. void stampa(graph *G)
  44. {
  45. int i,ne=0;
  46. edge *e;
  47.  
  48. if (G!=NULL)
  49. {
  50. printf("\nIl grafo ha %d vertici\n",G->nv);
  51. for (i=0;i<G->nv;i++)
  52. {
  53. e=G->adj[i];
  54. printf("\n%d",i);
  55. while (e!=NULL)
  56. {
  57.  
  58. printf(" --> %d ",e->key);
  59. e=e->next;
  60. ne++;
  61. }
  62. }
  63. printf("\n\nIl grafo ha %d archi\n",ne);
  64. }
  65. }
  66.  
  67. int main()
  68. {
  69. graph *G,*Int = NULL;
  70. int n;
  71.  
  72. do
  73. {
  74. printf("Inserire il num di nodi dei grafi:");
  75. scanf("%d",&n);
  76. G=inizializza_grafo(n);
  77. stampa(Int);
  78. printf("\n premere 0 per uscire \n");
  79. scanf("%d",&n);
  80. }
  81. while(n!=0);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement