Oppure

Loading
20/06/11 10:12
Bonny
Questo programma dovrebbe creare un albero binario ordinato in base al cognome e a parita di cognome, in base al nome
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct elementAlbero{
        int mat;
        char nome[10];
        char cogn[10];
        struct elementAlbero *sx;
        struct elementAlbero *dx;
}tree;
typedef tree *Tree;
int compareT(char [],char [], Tree);
void inorder(Tree);
Tree creaTree(int,char [],char [], Tree);

main(){
  int i;
  int m;
  char n[10];
  char c[10];
  Tree T = NULL;
  
   for(i=0;i<4;i++){
      printf("\ncogn: ");    scanf("%s",c);    
      printf("\nnome: ");    scanf("%s",n);  
      printf("\nmatr: ");    scanf("%d",&m);      
      T = creaTree(m,n,c,T);      
   }
   printf("\n\n ");
   inorder(T);
system("pause");
}
int compareT(char c[], char n[], Tree nodo ){
     
    if(strcmp(c , nodo->cogn) == 0){            
       if(strcmp(n, nodo->nome) > 0)return 1;      
    }else{        
        if(strcmp(c, nodo->cogn) > 0){
             return 1;
         }else {
             if(strcmp(c, nodo->cogn) < 0){
                 return 0;
             }
         }
     }      
}


Tree creaTree(int m, char n[], char c[], Tree t){
     
        if(t == NULL){
             t = (Tree) malloc(sizeof(tree));
             strcpy(t->cogn, c);
             strcpy(t->nome, n);
             t->mat = m;
             t->sx = NULL;
             t->dx = NULL;
             return t;
        }else{
              int y = compareT(c, n, t);
              if(y == 0){
                   t->sx = creaTree(m, n, c, t->sx);
                   return t;
              }else{
                   t->dx = creaTree(m, n, c, t->dx);
                   return t;                    
              }
        }
}
void inorder(Tree t){
   if(t != NULL){
        inorder(t->sx);
          printf("%s %s %d\n",t->cogn,t->nome,t->mat);
        inorder(t->dx);
        }     
}

non capisco perchè ordina solo in base al cognome .. grazie
Ultima modifica effettuata da Bonny 20/06/11 10:19
aaa
20/06/11 10:38
comina8
int compareT(char c[], char n[], Tree nodo)
{
    if(strcmp(c , nodo->cogn) == 0)
      {            
           if(strcmp(n, nodo->nome) > 0)
               return 1;
           else if(strcmp(n,nodo->nome)<0)
               return 0;
       }
    else
      {        
            if(strcmp(c, nodo->cogn) > 0)
                 return 1;
            else if(strcmp(c, nodo->cogn) < 0)
                 return 0;
      }
    //nel caso siano uguali
    return -1;
}


Il tuo problema stava nella prima if innestata.
Non ho controllato il resto del programma, ma ordinando comunque
in base al cognome dovrebbe essere corretto.
Penso fosse un errore solo in questa funzione.
Testalo poi vediamo.
Ultima modifica effettuata da comina8 20/06/11 10:39
aaa