Last active
May 25, 2019 00:53
-
-
Save filiafobico/19f03ce0f13b0fdefe6b6f05fcf977c4 to your computer and use it in GitHub Desktop.
Implementação de uma pilha para inverter palavras de uma frase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #define TAM_PALAVRA 20 | |
| #define QTD_PALAVRAS 10 | |
| #define DELIMITADOR '\n' | |
| // Define a estrutura da Pilha | |
| typedef struct { | |
| int pos; | |
| int pilha[TAM_PALAVRA]; | |
| } Pilha; | |
| // Inicia a 'pos' = '0' | |
| void inicia(Pilha *pilha) { | |
| pilha->pos = 0; | |
| } | |
| // Inicializa todas as pilhas | |
| void iniciarTodasPilhas(Pilha *pilhas) { | |
| for (int i=0; i<QTD_PALAVRAS; i++) inicia(&pilhas[i]); | |
| } | |
| // Verifica se a pilha está vazia | |
| int isVazia(Pilha *pilha) { | |
| return pilha->pos == 0 ? 1 : 0; | |
| } | |
| // Verifica se a pilha está cheia | |
| int isCheia(Pilha *pilha) { | |
| return pilha->pos == TAM_PALAVRA ? 1 : 0; | |
| } | |
| // Insere item na pilha | |
| void inserir(Pilha *pilha, char item) { | |
| if (isCheia(pilha) == 1) return; | |
| pilha->pilha[pilha->pos++] = item; | |
| } | |
| // Remove item da pilha | |
| char remover(Pilha *pilha) { | |
| if (isVazia(pilha) == 1) return ' '; | |
| return pilha->pilha[--pilha->pos]; | |
| } | |
| // Remove e printa todos os caracteres da pilha | |
| char removerPalavraRecursivo(Pilha *pilha) { | |
| char c = remover(pilha); | |
| // Printa qualquer caractere exceto o DELIMITADOR | |
| if (c != DELIMITADOR) printf("%c", c); | |
| // Espaço é o fim da palavra | |
| if (c == ' ') return ' '; | |
| return removerPalavraRecursivo(pilha); | |
| } | |
| // Desmonta a pilha de cada palavra da frase | |
| void removerFraseInteira(Pilha *pilhas, int n) { | |
| for (int i=0; i<=n; i++) removerPalavraRecursivo(&pilhas[i]); | |
| } | |
| // Recebe cada caractere digitado | |
| int recebeFrase(Pilha *pilhas) { | |
| char c = ' '; | |
| int n = 0; | |
| // Recebe cada tecla digitada | |
| while (c != DELIMITADOR) { | |
| c = getchar(); | |
| // quando teclar 'espaço' muda a pilha que recebe os caracteres | |
| if (c == ' ') n++; | |
| inserir(&pilhas[n], c); | |
| }; | |
| return n; | |
| } | |
| void main() { | |
| Pilha pilha[QTD_PALAVRAS]; | |
| iniciarTodasPilhas(&pilha[0]); | |
| removerFraseInteira(&pilha[0], recebeFrase(&pilha[0])); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment