home *** CD-ROM | disk | FTP | other *** search
/ ftp.disi.unige.it / 2015-02-11.ftp.disi.unige.it.tar / ftp.disi.unige.it / pub / .person / CataniaB / teach-act / testi-esami / labo-9.99 / parte2.c < prev    next >
C/C++ Source or Header  |  1999-10-10  |  1KB  |  87 lines

  1. /* Esame 20 settembre '99 - parte 2 */
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. #define MAX 30
  7.  
  8. typedef struct node *tree;
  9.  
  10. struct node
  11. {
  12.   int el;
  13.   tree left,right;
  14. };
  15.  
  16.  
  17. tree empty()
  18. {
  19.   return NULL;
  20. }
  21.  
  22.  
  23. void insert(int i, tree *t)
  24. {
  25.   if (*t==empty()) /* caso base: albero vuoto */
  26.     {
  27.       *t=(tree) malloc(sizeof(struct node));
  28.       (*t)->el=i;
  29.       (*t)->left=empty();
  30.       (*t)->right=empty();
  31.     }
  32.   else if (i<(*t)->el) /* passo induttivo, sottoalbero sinistro */
  33.     insert(i,&((*t)->left));
  34.   else if (i>(*t)->el) /* passo induttivo, sottoalbero destro */
  35.     insert(i,&((*t)->right));
  36.  
  37. /* nota bene: nel caso i==(*t)->el non fa nulla! */        
  38. }   
  39.  
  40.  
  41. void print(tree t)
  42. {
  43.   if (t!=empty()) /* se l'albero e` vuoto non stampo nulla */
  44.     {
  45.       print(t->left);
  46.       printf(" %d",t->el);
  47.       print(t->right);
  48.     }
  49. }
  50.  
  51. void dispose(tree *t)
  52. {
  53.   if (*t!=empty())
  54.     {
  55.       dispose(&((*t)->left));
  56.       dispose(&((*t)->right));
  57.       free(*t);
  58.       *t=empty();
  59.     }
  60. }
  61.  
  62. int main(void)
  63. {
  64.   char fname[MAX];
  65.   tree t=empty();
  66.   FILE *fd=NULL;
  67.   int i;
  68.  
  69.   printf("Enter file name: ");
  70.   scanf("%s",fname);
  71.   if (fd=fopen(fname,"r"))
  72.     {
  73.       while (fscanf(fd,"%d",&i)==1 && i!=-1)
  74.       insert(i,&t);
  75.       printf("Tree from file %s: ",fname);
  76.       print(t);
  77.       printf("\n");
  78.       dispose(&t);
  79.       printf("Now is deleted: ");
  80.       print(t);
  81.       printf("\n");
  82.     }
  83.   else
  84.     printf("Error opening file %s\n",fname);
  85.   fclose(fd);   
  86. }
  87.