Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #define MAX 100
- struct Pilha{
- char vetor[MAX];
- int topo;
- };
- int iniciaPilha(struct Pilha *pilha){
- pilha->topo = -1;
- }
- int vaziaPilha(struct Pilha *pilha){
- if(pilha->topo == -1){
- return 1;
- }else{
- return 0;
- }
- }
- int cheiaPilha(struct Pilha *pilha){
- if(pilha->topo == MAX - 1){
- return 1;
- }else{
- return 0;
- }
- }
- void push(struct Pilha *pilha, int caracter){
- //Encerra o programa em caso de overflow
- if(cheiaPilha(pilha)){
- printf("Expressao muito grande.\n");
- exit(0);
- }
- pilha->vetor[ ++(pilha->topo) ] = caracter;
- }
- char pop(struct Pilha *pilha){
- //O programa não tentará remover com a pilha vazia
- char caracter = pilha->vetor[ pilha->topo ];
- --(pilha->topo);
- return caracter;
- }
- char topoPilha(struct Pilha *pilha){
- //Se a pilha estiver vazia, a comparação vai dá diferente, e a expressão será considerada inválida pois existe parentese de fechamento sem um parentese de abertura, o retorno impede underflow
- if(vaziaPilha(pilha)){
- return '0';
- }else{
- return pilha->vetor[ pilha->topo ];
- }
- }
- -----------------------------------------------------------------
- #include <stdio.h>
- #include <string.h>
- #include "PILHA_SEQ.h"
- int main(){
- char string[1001];
- int count, tam, correto;
- while(1){
- gets(string);
- //Se a entrada for vazia, o laço é quebrado
- if(strlen(string) == 0) break;
- //Inicializa a pilha que será utilizada
- struct Pilha pilha;
- iniciaPilha(&pilha);
- //Salva o tamanho da String
- tam = strlen(string);
- //A expressão é dada como valida até que se encontre um erro
- correto = 1;
- for(count = 0; count < tam; count++){
- if(string[count] == '(' || string[count] == '{' || string[count] == '['){
- push(&pilha, string[count]);
- }
- if(string[count] == ')'){
- if(topoPilha(&pilha) != '('){
- //Encontrado a expressão logo é considerada inválida e o laço é quebrado
- correto = 0;
- break;
- }else{
- pop(&pilha);
- }
- }else if(string[count] == '}'){
- if(topoPilha(&pilha) != '{'){
- correto = 0;
- break;
- }else{
- pop(&pilha);
- }
- }else if(string[count] == ']'){
- if(topoPilha(&pilha) != '['){
- correto = 0;
- break;
- }else{
- pop(&pilha);
- }
- }
- }
- //Checar se restou algum parenteses que não foi fechado na expressão
- if(vaziaPilha(&pilha)!=1) correto = 0;
- if(correto == 1){
- printf("Expressao correta.\n");
- }else{
- printf("Expressao incorreta.\n");
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment