-1

Whats is wrong in this code, i need to change the top of my stack. That's is my code and i need to change the top of my stack Also, i need to change my function imprime to print from the bottom to the top.

Something like 10 15 20, in the function pilha_imprime will print 20 15 10.

I need to understand how do that i'm learning stack in C++ and how it`s works.

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

struct no {
 float info;
 struct no* prox;
};
typedef struct no No;

struct pilha {
 No* prim;
};

pilha* pilha_cria (void){
    pilha* p = (pilha*) malloc(sizeof(pilha));
    p->prim = NULL;
    return p;
}

/* função auxiliar: insere no início */
No* ins_ini (No* l, float v)
{
     No* p = (No*) malloc(sizeof(No));
     p->info = v;
     p->prox = l;
     return p;
}
/* função auxiliar: retira do início */
No* ret_ini (No* l)
{
     No* p = l->prox;
     free(l);
     return p;
}

int vazia (pilha* p)
{
    return (p->prim==NULL);
}

void pilha_push (pilha* p, float v)
{
     p->prim = ins_ini(p->prim,v);
}

float pilha_pop (pilha* p)
{
     float v;
     if (vazia(p)) {
     printf("Pilha vazia.\n");
     exit(1); /* aborta programa */
     }
     v = p->prim->info;
     p->prim = ret_ini(p->prim);
     return v;
}

void pilha_libera (pilha* p)
{
     No* q = p->prim;
     while (q!=NULL) {
     No* t = q->prox;
     free(q);
     q = t;
     }
     free(p);
}

/* imprime: versão com lista */
void pilha_imprime (pilha* p)
{
 No* q;
 for (q=p->prim; q!=NULL; q=q->prox)
 printf("%f\n",q->info);
}

/* vai imprimir da base para o topo usando as funções já definidas e uma pilha auxiliar */
void imprime (pilha* p)
{
 No* q;
 for (q=p->prim; q!=NULL; q=q->prox)
 printf("%f\n",q->info);
}

void troca_topo(pilha* p)
{
    if(vazia(p))
    {
        printf("\nPilha Vazia!\n");
        return;
    }

    No* no_aux = (No*) malloc(sizeof(No)); // nó auxiliar.
    No* tmp = tmp->prox; // ponteiro que aponta para o primeiro nó da pilha.

    while(tmp->prox != NULL)// laco que percorre a pilha ate o ponteiro apontar para o ultimo nó.
        tmp = tmp->prox;

    // troca dos valores:
    no_aux->info = tmp->info; // elemento do nó auxiliar recebe o elemento do ultimo nó.
    tmp->info = (tmp->prox)->info; // o elemento do ultimo nó recebe o elemento do primeiro nó.
    (tmp->prox)->info = no_aux->info; // o primeiro nó recebe o elemento armazenado no nó auxiliar(que era o ultimo elemento).

    free(no_aux);// liberar a memoria do nó auxiliar.
}


int main(){

        /* Implementação de pilha com lista encadeada */
    pilha *p;
    p = pilha_cria();
    pilha_push(p,10);
    pilha_push(p,15);
    pilha_push(p,20);
    pilha_push(p,25);
    float v = pilha_pop(p);
    printf("Imprime : %f \n", v);
    printf("\n");

        /* vai imprimir do topo para a base, percorrendo a lista encadeada */
    pilha_imprime(p);
    printf("\n");

        /* vai imprimir da base para o topo usando as funções já definidas e uma pilha auxiliar */
    imprime(p);
    printf("\n");

        /*vai executar a função troca_topo, que troca o valor do topo com aquele abaixo, usando somente as funções push e pop*/
        // protótipo: void troca_topo(Pilha*p) - emite mensagem de erro para
        // pilha vazia ou com menos de dois elementos.
    troca_topo(p);
    pilha_imprime(p);

    pilha_libera(p);
    system("PAUSE");
    return 0;
}
Breno Sobral
  • 71
  • 2
  • 11
  • Use a debugger - it's a good thing - and also, your code does not compile. Make a [mcve]. – Ted Lyngmo May 29 '20 at 02:10
  • I`ll post the entire code. – Breno Sobral May 29 '20 at 02:23
  • Oh, no, that's not what _minimal_ means. **You** have to help others to help you. – Ted Lyngmo May 29 '20 at 02:40
  • 2
    Never post the entire code. It shows you have either done little to no debugging or inefficient debugging. What you want to do is try to understand and isolate the error by removing the parts of the code that do not contribute to the error. In a perfect world that would be `int main()` and a few lines in main, but the reality is you rarely get more than half way before the bug runs out of places to hide. – user4581301 May 29 '20 at 02:40
  • Check and resolve the compiler warnings. You should have at least one warning pointing out that there is no way in `No *tmp = tmp->prox;` for `tmp` to have a meaningful value before you use it to initialize itself. It's kind of like what's the value of `x` in `int x = x;`? – user4581301 May 29 '20 at 02:43

1 Answers1

0

Some functions are easier to write recursive, printing the stack backwards is one of them;

void imprime(No* no) {
    if (no != NULL) {
        imprime(no->prox);
        printf("%0.2lf\n", no->info);
    }
}

/* vai imprimir da base para o topo usando uma funções já definidas*/
void imprime(pilha* p)
{
    imprime(p->prim);
}

Switching top with bottom does not need a malloc. Memory is already allocated, all you have to do is switch the information. And you were using variable tmp before it a value was assigned, causing odd behavior.

void troca_topo(pilha* p)
{
    if(vazia(p))
    {
        printf("\nPilha Vazia!\n");
        return;
    }

    No* tmp = p->prim; // ponteiro que aponta para o primeiro nó da pilha.
    while(tmp->prox != NULL)// laco que percorre a pilha ate o ponteiro apontar para o ultimo nó.
        tmp = tmp->prox;

    // troca dos valores:
    float aux = tmp->info; // elemento auxiliar recebe o elemento do ultimo nó.
    tmp->info = p->prim->info; // o elemento do ultimo nó recebe o elemento do primeiro nó.
    p->prim->info = aux; // o primeiro nó recebe o elemento armazenado no auxiliar(que era o ultimo elemento).
}
Castro
  • 41
  • 3