2
I am making a stack, the data entered by the user has to allocate in descending order from the top, but whenever I have print the first at the top comes out as 0, that would be the highest value.
Here comes 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;
}
I think the idea of this exercise is for you to become familiar with push and pop operations. An interesting joke would be to use 1 stack and another auxiliary and check if the value of the top is greater than the value inserted, if it pops and stack in the auxiliary until you find the correct location. Then put the values back.
– Gustavo Fragoso