C stack, problem with output

2

I'm making a stack, the data entered by the user has to allocate from descending order from the top, but whenever I print the first one on the top it exits as 0 which would be the highest value.

Here's the code:

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

struct no{
int dado;
struct no *prox;
};
typedef no tno;
typedef tno *no_pont;

void inicia_pilha(no_pont *topo);
void push(no_pont *topo, int valor);
int pop(no_pont *topo);
int pilha_vazia(no_pont topo);
void imprime_pilha(no_pont topo);

int main() {
int x[9], y[9], n, aux, i;
no_pont pilha01, pilha02;

inicia_pilha(&pilha01);
inicia_pilha(&pilha02);

printf("Digite o tamanho das pilhas: ");
scanf("%d", &n);

printf("Valores da pilha um: ");
for(i=0;i<n;i++){
    scanf("%d", &x[i]);
}

printf("Valores da pilha dois: ");
for(i=0;i<n;i++){
    scanf("%d", &y[i]);
}

//odenando para crescente
for(i=1;i<=n;i++){
if( x[i] < x[i-1] ){
    aux = x[i-1];
    x[i-1]=x[i];
    x[i]=aux;
}
}

for(i=1;i<=n;i++){
if( y[i] < y[i-1] ){
    aux = y[i-1];
    y[i-1]=y[i];
    y[i]=aux;
}
}

//colocando os valores na pilha
for(i=0;i<n;i++){
push(&pilha01,x[i]);
}

for(i=0;i<n;i++){
push(&pilha02,y[i]);
}

//-------------//------------//

imprime_pilha(pilha01);
imprime_pilha(pilha02);


return 0;
}

void inicia_pilha(no_pont *topo){
*topo=NULL;
}

void push(no_pont *topo, int valor){
no_pont novo;
novo=(no_pont)malloc(sizeof(tno));
if(novo!=NULL){
    novo->dado = valor;
    novo->prox = *topo;
    *topo = novo;
} else{
    printf("Sem memoria disponivel\n");
}
}

int pop(no_pont *topo){
no_pont aux;
int valor;

valor=(*topo)->dado;
aux=*topo;
*topo= (*topo)->prox;

free(aux);
return valor;
}

void imprime_pilha(no_pont topo){
if(topo==NULL) printf("A pilha esta vazia!\n");
else{
    printf("A pilha e: ");

    while(topo!=NULL){
        printf("%d ",topo->dado);
        topo=topo->prox;
    }
    printf("\n");
}
}

int pilha_vazia(no_pont topo){
return topo==NULL;
}
    
asked by anonymous 28.09.2017 / 23:27

1 answer

2

Hello friend, your ordering is not very cool try to use this function

void ordenarLista(int* lista, int size) {
    int i, j, aux;
    for(i = 0; i < size -1; ++i){
        for(j = i +1; j < size; ++j){
            if(lista[i] > lista[j]){
                aux = lista[i];
                lista[i] = lista[j];
                lista[j] = aux;
            }
        }
   } 
}

This is the method of ordering bubble is very slow but it works, another way to solve this problem was to do the insertion in your already ordering array. Just a question if it's a stack why sort?

    
29.09.2017 / 01:52