String chained list within a struct

Asked

Viewed 116 times

1

Hello. I’m doing a job where I need to store words in a list that must be inside a tree struct. I don’t know why the code stops inserting in the list shortly after moving to the next key/line.

The idea is: each tree key has a list of strings(words) and depending on the parameter given along with the word, go to a certain key. I’m using a simply chained list to store the strings.

The read file has a number of lines: número palavra palavra palavra...

Follows entire code:

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

/*funções auxiliares para manipulação de listas */
typedef struct lista{
    char* palavra;
    struct lista *prox;
}Lista;

Lista *iniciaLista(char *palavra) {
    Lista *novo = (Lista *)malloc(sizeof(Lista));
    novo->palavra = (char *)malloc(strlen(palavra)+1);
    strncpy(novo->palavra, palavra, strlen(palavra)+1);
    novo->prox = NULL;
    return novo;
}

Lista* inserirLista(Lista* l, char *palavra){
    Lista* novo = (Lista*)malloc(sizeof(Lista));

    printf("Alocou um ponteiro novo para lista\n");
    novo->prox = NULL;

    if (l == NULL){
        return novo;
    }

    Lista* aux = l;

    while(aux->prox != NULL){
        aux=aux->prox;
    }

    aux->prox = novo;

    return l;
}

//Lista* buscaLista (Lista* l, int valor){
//    if(l->info == valor){
//      return l;
//    }
//  if(l->prox != NULL){
//      return buscaLista(l->prox, valor);
//  }
//  return NULL;
//}

void imprimirLista(Lista* l){
    do{
        printf("%s ", l->palavra);
        l= l->prox;
    }while(l != NULL);
}

typedef struct no{
    int data;
    struct no *esq,*dir;
    int altura;
    int qtdFrases;
    int qtdPalavras;
    Lista *palavras;
}No;

int fatorBalance(No *raiz){
    int lh,rh;
    if(raiz==NULL)
        return(0);

    if(raiz->esq==NULL)
        lh=0;
    else
        lh=1+raiz->esq->altura;

    if(raiz->dir==NULL)
        rh=0;
    else
        rh=1+raiz->dir->altura;

    return(lh-rh);
}

int fAltura(No *raiz){
    int lh,rh;
    if(raiz==NULL)
        return(0);

    if(raiz->esq==NULL)
        lh=1;
    else
        lh=1+raiz->esq->altura;

    if(raiz->dir==NULL)
        rh=1;
    else
        rh=1+raiz->dir->altura;

    if(lh>rh)
        return(lh);

    return(rh);
}

No * rotacionaDir(No *x){
    No *y;
    y = x->esq;
    x->esq = y->dir;
    y->dir = x;
    x->altura = fAltura(x);
    y->altura = fAltura(y);
    return(y);
}

No * rotacionaEsq(No *x){
    No *y;
    y = x->dir;
    x->dir = y->esq;
    y->esq = x;
    x->altura = fAltura(x);
    y->altura = fAltura(y);

    return(y);
}

No * rotRR(No *raiz){
    raiz=rotacionaEsq(raiz);
    return(raiz);
}

No * rotLL(No *raiz){
    raiz=rotacionaDir(raiz);
    return(raiz);
}

No * rotLR(No *raiz){
    raiz->esq=rotacionaEsq(raiz->esq);
    raiz=rotacionaDir(raiz);

    return(raiz);
}

No * rotRL(No *raiz){
    raiz->dir=rotacionaDir(raiz->dir);
    raiz=rotacionaEsq(raiz);
    return(raiz);
}

No * insereArvore(No *raiz, int categoria, char* palavra){
    if(raiz==NULL){
        raiz=(No*)malloc(sizeof(No));
        raiz->data = categoria;
        raiz->esq=NULL;
        raiz->dir=NULL;
        raiz->qtdFrases = 0;
        raiz->qtdPalavras = 1;
        printf("\nCategoria nao existente\n");
        raiz->palavras = iniciaLista(palavra);
        printf("Inseriu na NULL a palavra ");
    }
    else{
        if(categoria > raiz->data){
            raiz->dir = insereArvore(raiz->dir, categoria, palavra);
            if(fatorBalance(raiz) == -2){
                if(categoria > raiz->dir->data){
                    raiz = rotRR(raiz);
                }
                else{
                    raiz = rotRL(raiz);
                }
            }
        }
        else if(categoria < raiz->data){
                raiz->esq = insereArvore(raiz->esq, categoria, palavra);
                if(fatorBalance(raiz) == 2){
                    if(categoria < raiz->esq->data){
                        raiz = rotLL(raiz);
                    }
                    else{
                        raiz = rotLR(raiz);
                    }
                }
        }
        else{ // se a raiz->data for igual ao valor recebido (já tiver a categoria na árvore)
            raiz->qtdPalavras = raiz->qtdPalavras + 1;
            printf("\nCategoria Existente\n");
            printf("Quantidade de palavras na categoria: %d\n", raiz->qtdPalavras);
            inserirLista(raiz->palavras, palavra);
            printf("Inseriu a palavra ");
        }

        raiz->altura = fAltura(raiz);

        return raiz;
    }
    return raiz;
}

No * buscaArvore(No *no, int valor){// se achar o valor, retorna o nó onde está localizado. caso n ache, retorna NULL
    if (no == NULL){
        return NULL;
    }
    if (valor == no->data){
        return no;
    }
    if (valor < no->data){
        return buscaArvore(no->esq, valor);
    }
    else{
        return buscaArvore(no->dir, valor);
    }

    return NULL;
}


void inorder(No *T){
    if(T!=NULL){
        inorder(T->esq);
        printf("%d\n", T->data);
        imprimirLista(T->palavras);
        inorder(T->dir);
    }
}

int toint(char categoria[]){
    int len = strlen(categoria);
    int i, num = 0;
    for (i = 0; i < len; i++){
        num = num + ((categoria[len - (i + 1)] - '0') * pow(10, i));
    }
    return num;
}

int main(){
    FILE* arquivo = NULL;
    char linha[300];
    char* coisa;
    int categoria;
    No* arv = NULL;

    arquivo = fopen("frases.txt", "r");
    if(arquivo == NULL){
        printf("Erro ao ler o arquivo..");
    }
    printf("Antes de ler\n");
    while (!feof(arquivo)){ // loop de linhas
        coisa = fgets(linha, 300, arquivo);
        if (coisa){
            char *pedaco = NULL;
            int lenPalavra;
            pedaco = strtok(linha, " ");
            categoria = toint(pedaco); //salva o numero como int (antes do while de palavras pois é o primeiro termo)

            while(pedaco){ // loop de palavras
                lenPalavra = strlen(pedaco);
                if(lenPalavra > 3){
                    for(int i = 0; pedaco[i]; i++){ //loop para transformar a string 'pedaco' em minuscula
                        pedaco[i] = tolower(pedaco[i]);
                    }
                    arv = insereArvore(arv, categoria, pedaco);
                    printf("%s (%d) na chave\n", pedaco, categoria);

                }
                pedaco = strtok(NULL, " ");
            }
            printf("terminou a linha\n");
            //arv = buscaArvore(arv, categoria);
            //arv->qtdFrases = arv->qtdFrases + 1;
        }
    }
    //arv = insereArvore(arv, -3, "maca");
    inorder(arv);
    printf("\n\nCompila plz..\n");
}
  • In this loop: while(substring){ lenPalavra = strlen(substring); if(lenPalavra > 3){ for(int i = 0; substring[i]; i++){ pedaco[i] = tolower(substring[i]); } arv = insereArvore(arv, cat, substring); printf("%s (%d)\n", substring, cat); } pedaco = strtok(NULL, " "); } at no time do you modify substring. I didn’t see the statement either pedaco.

  • sorry, the piece was supposed to be "substring". I’ll edit

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.