El problema está en el árbol.

   - La función addnode() debe recibir un doble puntero a un nodo.
   - root debe estar inicializado a NULL.

Código corregido:


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define WORDLEN        20

typedef struct b_tree
{
    struct b_tree *next, *prev;
    char *word;
    unsigned count;
} node;

void addnode(node **p, char *word);
int treeprint(node *p);
int getword(char *s, unsigned len);

// arbolBin: count word frecuency from stdin
int main()
{
    char * word;
    node * root = NULL;

    word = (char*) malloc(WORDLEN+1);

    while (getword(word, WORDLEN) > 0)
        addnode(&root, word);

    treeprint(root);

    free(word);

    return 0;
}

//char *strdup(char *p);

void addnode(node **p, char *word)
{
    int cond;

    if (*p == NULL) {
        *p = (node*) malloc(sizeof(node));
        (*p)->word = strdup(word);
        (*p)->count = 1;
        (*p)->prev = (*p)->next = NULL;

        return;
    }

    if ((cond = strcmp(word, (*p)->word)) < 0)
        addnode(&(*p)->prev, word);
    else if (cond > 0) {
        addnode(&(*p)->next, word);
    } else
        (*p)->count++;

    return;
}

int treeprint(node *p)
{
    static int nlines = 0;

    if (p == NULL)
        return 0;

    treeprint(p->prev);
    printf("%3d\t%s", p->count, p->word);
    treeprint(p->next);

    free(p);

    return ++nlines;
}

int getword(char *s, unsigned len)
{
    int i, c;

    while (!isalpha(c = getchar()) && c != EOF);

    for (i = 0; isalpha(c) && i < len; c = getchar(), i++)
        *s++ = c;
    *s = '\0';

    return i;
}
_______________________________________________
Lista de correo Programacion.
[email protected]
http://listas.fi.uba.ar/mailman/listinfo/programacion

Responder a