Chained list within Chained list

Asked

Viewed 635 times

2

I’m struggling with chained lists inside a chained list. The program is a card game in which there is a doubly chained list of players and within each node of that list, a list (the hand) of cards. I’m having trouble adding a letter to the list of letters. How to properly access the player node and how to access the first position of the list within this node?

My structs:

typedef struct Carta{
    int valor;
    char naipe;
}Carta;

typedef struct Cartas{
    Carta Item;
    struct Cartas *Prox_carta;
    struct Cartas *Primeiro, *Ultimo;
    int Tamanho_Mao;
}Cartas;

typedef struct Jogador {
    int id_jogador;
    Cartas *Primeira_mao;
    struct Jogador *Prox, *Ant;
    struct Jogador *Prim_Jogador, *Ult_Jogador;
    int Tamanho;
}Jogador;

The function to try to add cards:

int Adiciona_Carta(Jogador *jogadores, Cartas *mao, int x, Carta carta){

    Jogador *aux;
    Cartas *novaCarta, *aux2;
    novaCarta = (Cartas*)malloc(sizeof(Cartas));
    novaCarta->Prox_carta = NULL;
    novaCarta->Item.naipe = carta.naipe;
    novaCarta->Item.valor = carta.valor;
    aux = jogadores->Prim_Jogador;

    while (jogadores->id_jogador != x){
        aux = aux->Prox;
    }
    aux2 = aux->Primeira_mao;
    mao->Primeiro = aux->Primeira_mao;
    if (aux->Primeira_mao == NULL){
        Cria_Mao_Carta(mao);
        mao->Primeiro = novaCarta;
        mao->Tamanho_Mao++;
    } 
    if (carta.valor > aux2->Item.valor){
        novaCarta->Prox_carta = mao->Primeiro;
        mao->Primeiro = novaCarta;
        mao->Tamanho_Mao++;
    }
    for (aux2 ;; aux2 = aux2->Prox_carta){
        if(carta.valor > aux2->Prox_carta->Item.valor){
            novaCarta->Prox_carta = aux2->Prox_carta;
            aux2->Prox_carta = novaCarta;
            mao->Tamanho_Mao++;
        }
        if(aux2->Prox_carta == NULL){
            aux2->Prox_carta = novaCarta;
            novaCarta->Prox_carta = NULL;
        }
    }
}

1 answer

1

I recommend, first of all, creating a separate structure for the list.

typedef struct Conteudo{
int valor;
char naipe;
}Conteudo; 

typedef struct Cartas{
    Conteudo Item;
    struct Cartas *Prox_carta;
}Carta;

typedef struct ListaCartas {
    carta *primeiro, *ultimo;
    int tamanho;
}

makes the same scheme with the players, it is much more clear what ce is doing. it was quite confused its structure this way.

and for God’s sake, don’t use aux for everything no, give a name to variable that another person who is reading your code will understand =/

can not understand your function code without knowing where the aux of type Player was, ce did not specify that the function Creator

Browser other questions tagged

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