#include #include #include #define MAX 10000 struct morsetree{ char letter; struct morsetree *dash; struct morsetree *dot; }; struct morsetree* create(char l){ struct morsetree* new = calloc(1, sizeof(struct morsetree)); new->letter = l; new->dot = NULL; new->dash = NULL; return new; } struct morsetree* add(struct morsetree *tree, char *morse, char letter){ struct morsetree *this; int i, size; this = tree; size = strlen(morse); for(i = 0; i < size; i++) { if(morse[i] == '.') { if(this->dot == NULL){ this->dot = create('*'); } this = this->dot; } else if(morse[i] == '-'){ if(this->dash == NULL){ this->dash = create('*'); } this = this->dash; } } this->letter = letter; } void destroy(struct morsetree *root){ if(root == NULL) return; destroy(root->dot); destroy(root->dash); free(root); root = NULL; } void search(struct morsetree* root, char* decode){ struct morsetree* this = root; int i = 0; for(i == 0; i <= strlen(decode); i++){ if(i == strlen(decode) && decode[strlen(decode)-1] == ' '){ return; } if(decode[i] == ' ' || decode[i] == '\n' || decode[i] == '\0'){ printf("%c", this->letter); this = root; } if(decode[i] == '/'){ printf(" "); } else{ if(decode[i] == '.'){ this = this->dot; } else if(decode[i] == '-'){ this = this->dash; } } } } int main (){ struct morsetree *root = create('*'); add(root, ".-", 'A'); add(root, "-..." ,'B' ); add(root, "-.-.", 'C' ); add(root, "-..", 'D'); add(root, ".", 'E'); add(root, "..-.", 'F'); add(root, "--.", 'G'); add(root, "....", 'H'); add(root, "..", 'I'); add(root, ".---", 'J'); add(root, "-.-", 'K'); add(root, ".-..", 'L'); add(root, "--", 'M'); add(root, "-.", 'N'); add(root, "---", 'O'); add(root, ".--.", 'P'); add(root, "--.-", 'Q'); add(root, ".-.", 'R'); add(root, "...", 'S'); add(root, "-", 'T'); add(root, "..-", 'U'); add(root, "...-", 'V'); add(root, ".--", 'W'); add(root, "-..-", 'X'); add(root, "-.--", 'Y'); add(root, "--..", 'Z'); add(root, ".----", '1'); add(root, "..---", '2'); add(root, "...--", '3'); add(root, "....-", '4'); add(root, ".....", '5'); add(root, "-....", '6'); add(root, "--...", '7'); add(root, "---..", '8'); add(root, "----.", '9'); add(root, "-----", '0'); while(1){ char line[MAX]; fgets(line, MAX, stdin); line[strlen(line)-1] = '\0'; if(line[0] == '\n'){ break; } search(root, line); printf("\n"); printf("\n"); } destroy(root); }