I've reformatted the code and will go through it for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
using namespace std;
struct tipo_pilha
{
char elemento [100];
int indice_topo;
};
tipo_pilha push(tipo_pilha pilha, char elemento)
{
if (pilha.indice_topo+1<=100)
{
pilha.indice_topo++;
pilha.elemento[pilha.indice_topo]= elemento;
}
else
cout<<"pilha cheia!!"<<endl;
return pilha;
}
tipo_pilha pop(tipo_pilha pilha)
{
if (pilha.indice_topo>=0)
pilha.indice_topo--;
else
cout<< "pilha vazia!!"<<endl;
return pilha;
}
char top(tipo_pilha pilha)
{
if (pilha.indice_topo>=0)
return pilha.elemento[pilha.indice_topo];
else
cout<< "Pilha vazia!!"<<endl;
}
int main(int argc, char *argv[])
{
tipo_pilha pilha;
pilha.indice_topo = -1;
cout<< "Digite uma palavra"<< endl;
char letra = 0;
while (letra!= '+')
{
cin>>letra;
if (letra!= '+')
pilha = push (pilha, letra);
}
cout<<"A palavra em ordem inversa eh:";
while (pilha.indice_topo>=0)
{
cout << top(pilha);
pilha = pop(pilha);
}
return 0;
}
|
Lines 1, 2 declare
cin
and
cout
that you use to do input/output later on.
Line 4-8 declare a data for yor stack. Its a record (
struct
in C++) that has 100 elements of type char and stack pointer that tracks the stack as it's used. It is used as an index into the arra of elements.
There are three things you can do to your stack, you can
push an item onto it,
pop an item that was previously pushed, and you can take a look at the top element.
The functions that follow implement the push, pop and top operations, and finally main reads stuff in from user and outputs it in reverse order by using the stack.
Lines 10-21 define the push function. It takes the stack data structure and the character you want to push. If the stack is not full, it increments the index, and puts the character passed in into the array of elements at the new index position.
Lines 23-30 have the pop function. It takes the stack data structure and just discards the top item.
Lines 32-38 have the top function. If the stack is not empty it returns the character that's on top of the stack; that is, the character at the index position.
Liness 40-62 have the test harness. It reads characters in and pushes them onto the stack until the user enters
+, then it writes them all out in reverse order.