Queue with circular chained list with head

0

Deploy a queue to a circular head chained list (do functions that implement Insertion and Removal operations). The first element of the queue will be in the second cell and the last element will remain in the cell anterior to head.

Celula *inserir(Celula *fim, Pessoa *p){
    Celula *nova = (Celula*) malloc(sizeof(Celula));
    nova->ptrpessoa = p;
    nova->prox = fim->prox;
    fim->prox = nova;
    fim = nova;
    return fim;
}

void remover(Celula *ini){
    Celula *li = ini->prox;
    ini->prox = li->prox;
    printf("OPA");
    free(li);
}

Queue declaration

Fila ini;
Fila fim;

To have a head, what do I do? I tried that way.

Celula cini, cfim;
ini = &cini;  /aqui o  ini da fila recebe o endereço d cini?
fim = ini; /aqui o  final  da fila recebe o endereço d cini?

/ and is it circular here?     ini- > prox = ini;

    
asked by anonymous 30.09.2015 / 17:17

1 answer

2

First of all, for the list to have a head and to be circular it is necessary to create that head and make it point to itself. Dynamically, that would be it:

Celula *cabeca = (Celula*) malloc(sizeof(Celula));
cabeca->prox = cabeca;

Second, if what you want is a queue, you also need to save a reference to the last element (for efficiency) - which at the beginning is equal to the head:

Celula *ultimo = cabeca;

From here your current code should work correctly - inserir(ultimo, p) creates a node after the last one updating it, and remover(cabeca) removes the first element that is not the head (hint: it is interesting to also check if the queue is empty - which occurs when cabeca == ultimo ).

Your attempt to declare, on the other hand, has some minor issues:

Celula cini, cfim; // Criou duas células, mas você só precisa de uma
ini = &cini;       // ok
fim = ini;         // ok, mas faltou ini->prox = ini pra ser circular
    
30.09.2015 / 19:47