1
I need to solve a question, she asks me to display the contents of a stack in reverse form, I thought a lot and I came to the conclusion that it is only possible to create an auxiliary stack and transferring the contents from one stack to another, so the result of the auxiliary stack would be the reversed stack.
The idea is easy, but I’m having a lot of trouble creating this auxiliary stack, I’m beginner with ADT’s and I’m breaking my head to solve this.
My code:
#include<iostream>
using namespace std;
struct no{
char n;
no *prox;
};
struct pilha{
no *topo;
};
int menu(){
int op;
cout << "\n1. Inserir na pilha\n";
cout << "2. Remover da pilha\n";
cout << "3. Imprimir pilha\n";
cout << "4. Imprimiir pilha invertida\n";
cout << "5. Sair\n";
cout << "Opcao: ";
cin >> op;
return op;
}
no* criarNo(){
char num;
cout << "Qual caractere deseja inserir: ";
cin >> num;
no *novo = new no;
novo->n = num;
novo->prox = NULL;
return novo;
}
void inserirPilha(pilha *inicio){
no *insere = criarNo();
if(inicio->topo == NULL){
inicio->topo = insere;
}
else{
insere->prox = inicio->topo;
inicio->topo = insere;
}
}
void imprimirPilha(pilha *inicio){
if(inicio->topo == NULL)
cout << "pilha vazia\n";
else{
no *aux = inicio->topo;
while(aux->prox != NULL){
cout << aux->n << " ";
aux = aux->prox;
}
cout << aux->n << " ";
}
}
void imprimirPilhaInvertida(pilha *inicio){
//Função para exibir a pilha auxiliar.
}
void removerPilha(pilha *inicio){
if(inicio->topo == NULL)
cout << "Fila vazia\n";
else
inicio->topo = inicio->topo->prox;
}
int main(){
int opcao;
pilha *inicio = new pilha;
inicio->topo = NULL;
while(true){
opcao = menu();
switch(opcao){
case 1:
inserirPilha(inicio);
break;
case 2:
removerPilha(inicio);
break;
case 3:
imprimirPilha(inicio);
break;
case 4:
imprimirPilhaInvertida(inicio);
break;
case 5:
return -1;
default:
cout << "Opcao invalida\n";
break;
}
}
return 0;
}
Have you thought about
removerPilha(topo)
followed byinserirPilha(topo_pilha_auxiliar)
, until the original stack is empty?– anonimo