0
Good afternoon, you guys. I hope I’m publishing it right, because I’m new to the forum and new to programming. So, on a question that I am, more specifically in "Simple Chained Lists", is that the function below should eliminate the first half of the chained list. I would have to go through the entire list to get half off the list, in case it’s even.
Am I doing it right?
If you can help me with the code below, you are most welcome!!
Function below:
// (c) Remove a primeira metade da Lista. Caso a lista possua um número ímpar de elementos,
// considere que a primeira metade possui mais elementos
// (Ex: se a lista possuir 5 elementos, a primeira metade possui os 3 primeiros elementos).
// Se a lista tiver vazia, nada acontece.
void removePrimeiraMetade(Lista *L) {
    // IMPLEMENTE ESTA FUNÇÃO
    //Estou pensando no código
    if (listaEstavazia(L)){
      return;
    }
    else{
      No *p = L->inicio;
      No *anterior = NULL;
      while (p != NULL){
        if (L->tamanho % 2 == 0){
          anterior->prox = no->prox;
          L->tamanho--;
        }
      }
    }
}
Struct _no, _produto and _lista (it’s not in order, but it’s here):
typedef struct _produto {
    int num_serie; // numero de série do produto
    char nome[64];
    double preço;
} Produto;
// struct que define um nó curcular duplamente encadeado
typedef struct _no {
    Produto *prod;
    struct _no *prox;
} No;
// struct que define uma Lista Ligada Simples
typedef struct _lista {
    No *inicio;
    No *fim;
    int tamanho; // numero de nós da lista
} Lista;
Code update above:
The code is basically like this, right?
if (listaEstaVazia(L)){
    return;
}
else {
    int tamanho = L->tamanho;
    if (tamanho % 2 == 0){
        for (int i=0; i<(tamanho / 2); i++){
            L->inicio = L->inicio->prox;
            L->tamanho--;
        }
    }
    else {
        double impar = round(L->tamanho / 2);
        for (int i=0; i<impar; i++){
            L->inicio = L->inicio->prox;
            L->tamanho--;
        }
    }
}
Take the list size and divide by 2, call this value loops. Then run a for that goes up to the amount of loops, for each cycle you remove the first item from the list.
– user201641
What if the list size is odd? For example, I have a list of size 5, the "half" is 3, and I must pick them up. It’s basically smeelhante when I make in even list.
– Manoel Kikachi Mendez
In this case, you decide whether to round up or down. If you are using a variable of type int, it will ignore the decimal places, which gives the effect of "rounding down".
– user201641
Got it. In this case, then, I must declare a new float variable?
– Manoel Kikachi Mendez
You can just divide the
L->tamanhofor 2, make afor loopthat traverses all nodes from the L->start to the node in question, deleting them and then changing the L->start to the final node– André