Invert stack values

Asked

Viewed 3,626 times

0

I’m trying to reverse the order of the stack elements using the loop while, but I’m not getting it.

pilha* inverte(pilha **p) {
    pilha *outra = cria(); //aloca e seta a qnt com 0
    while(vazia(&p)) {
         outra->dados[outra->qnt++] = (*p)->dados[(*p)->qnt];
        (*p)->qnt--;
    }
    return outra;
}

I’m trying to get current position.

  • 1

    The code is pretty weird, but only with this I don’t know if I can respond properly. You need to put something else to understand how you got there and if the problem isn’t elsewhere.

  • The stack is only of values.

  • Displaying an additional value. http://ideone.com/Q1QL37

1 answer

1


I have improved on several things, among them I have simplified the passing of parameter, no need to pass pointer. But the main mistake is that the operator >= could not be used in while. When it reaches 0 it has to stop, because of the = He was doing an extra operation. But there’s also a problem on the other side. He starts by picking up the content equivalent to the amount of elements in the stack. As index starts at 0, the last is quantity minus 1. With these two changes it works. But it’s still not releasing the memory (I know it’s something unnecessary in this example, but it’s good to get used to doing right always):

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

#define MAX 10

typedef struct pilha {
    int qnt;
    int dados[MAX];
} Pilha;
Pilha* cria() {
    Pilha *p = malloc(sizeof(Pilha));
    if (p != NULL) p->qnt = 0;
    return p;
}
void insere(Pilha *p, int valor) {
    p->dados[p->qnt] = valor;
    p->qnt++;
}
void exibe(Pilha *p) {
    for (int i = 0; i < p->qnt; i++) printf("%3d", p->dados[i]);
}
Pilha* inverte(Pilha *p) {
    Pilha *outra = cria();
    while (p->qnt > 0) {
        outra->dados[outra->qnt] = p->dados[p->qnt - 1];
        p->qnt--;
        outra->qnt++;
    }
    return outra;
}
int main() {
    Pilha *p = cria();
    insere(p, 32);
    insere(p, 45);
    insere(p, 78);
    exibe(p);
    p = inverte(p);
    printf("\n");
    exibe(p);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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