Baixe o app para aproveitar ainda mais
Prévia do material em texto
#include <stdio.h> #include <string.h> #include <ctype.h> #define TRUE 1 #define FALSE 0 typedef struct no { char info; struct no * prox; } TNo; typedef TNo * Stack; int isEmpty (Stack p) { // teste se a pilha está vazia if (p == NULL) return TRUE; else return FALSE; } void push (Stack * p, char n) { // empilhar um valor, ou seja, insere no topo da pilha TNo * novo; novo = (TNo *) malloc (sizeof (TNo)); novo->info = n; if (isEmpty (*p) == TRUE) novo->prox = NULL; else novo->prox = *p; *p = novo; } char pop (Stack * p) { // desempilha, ou seja, retira o valor situado no topo da pilha char n; TNo * aux; aux = *p; *p = (*p)->prox; n = aux->info; free (aux); return n; } char top (Stack p) { return p->info; } void initialize (Stack *p) { *p = NULL; } int analisaExpressao (char vet[]) { char desempilhado; int tam, pos, bemFormada; Stack pilha; initialize (&pilha); tam = strlen (vet); pos = 0; bemFormada = 1; while (bemFormada == 1 && pos < tam) { if (vet[pos] == '(' || vet[pos] == '[' || vet[pos] == '{') { push (&pilha, vet[pos]); } else if (vet [pos] == ')' || vet[pos] == ']' || vet[pos] == '}') { if (isEmpty (pilha) == FALSE) { desempilhado = pop (&pilha); switch (vet[pos]) { case ')': if (desempilhado != '(') bemFormada = 0; break; case ']': if (desempilhado != '[') bemFormada = 0; break; case '}': if (desempilhado != '{') bemFormada = 0; break; } } else bemFormada = 0; } pos++; } if (bemFormada == 0) return 0; else if (isEmpty(pilha) == FALSE) { while (isEmpty (pilha) == FALSE) pop (&pilha); return 0; } else return 1; } � void lerExpressao (char vet[]) { printf ("Digite a expressao: "); fgets (vet,99,stdin); fflush (stdin); } int main ( ) { char exp [100], resp; int result; do { lerExpressao (exp); result = analisaExpressao (exp); if (result == 1) printf ("Bem formada \n"); else printf ("Mal formada \n"); printf ("Deseja analisar outra expressao? (S/N) "); resp = toupper (getchar()); fflush (stdin); while (resp != 'S' && resp != 'N') { printf ("Digite S ou N: "); resp = toupper (getchar()); fflush (stdin); } } while (resp != 'N'); return 0; }
Compartilhar