Herowaree

ChecarExpressao_ENC.c

Nov 29th, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. struct No{
  6. char dado;
  7. struct No *proximo;
  8. };
  9.  
  10. struct Pilha{
  11. int tamanho;
  12. struct No *cabeca;
  13. };
  14.  
  15. void iniciaPilha(struct Pilha *pilha){
  16. pilha->tamanho = 0;
  17. pilha->cabeca = NULL;
  18. }
  19.  
  20. int tamanhoPilha(struct Pilha *pilha){
  21. return pilha->tamanho;
  22. }
  23.  
  24. int vaziaPilha(struct Pilha *pilha){
  25. if(pilha->tamanho == 0){
  26. return 1;
  27. }else{
  28. return 0;
  29. }
  30. }
  31.  
  32. char topoPilha(struct Pilha *pilha){
  33. if(vaziaPilha(pilha)) return '0';
  34.  
  35. return (pilha->cabeca)->dado;
  36. }
  37.  
  38. int push(struct Pilha *pilha, char caracter){
  39. struct No *novoNo;
  40. novoNo = malloc(sizeof(struct No));
  41.  
  42. if(novoNo == NULL) return 0;
  43.  
  44. novoNo->dado = caracter;
  45. novoNo->proximo = pilha->cabeca;
  46. pilha->cabeca = novoNo;
  47.  
  48. pilha->tamanho++;
  49.  
  50. return 1;
  51. }
  52.  
  53. char pop(struct Pilha *pilha){
  54. struct No *aux = pilha->cabeca;
  55.  
  56. //Retorno '0' impede o underflow
  57. int caracter;
  58. if(vaziaPilha(pilha)) return '0';
  59.  
  60. caracter = (pilha->cabeca)->dado;
  61. pilha->cabeca = aux->proximo;
  62. free(aux);
  63. pilha->tamanho--;
  64.  
  65. return caracter;
  66. }
  67.  
  68. int main(){
  69.  
  70. char string[1001];
  71.  
  72. scanf("%1000[^\n]", string);
  73.  
  74. struct Pilha pilha;
  75. iniciaPilha(&pilha);
  76.  
  77. int correto = 1, count, tam = strlen(string);
  78. for(count = 0; count < tam; count++){
  79. if(string[count] == '(' || string[count] == '{' || string[count] == '['){
  80. push(&pilha, string[count]);
  81. }
  82.  
  83. if(string[count] == ')'){
  84. if(topoPilha(&pilha) != '('){
  85. //Encontrado um erro, a expressão logo é considerada inválida e o laço é quebrado
  86. correto = 0;
  87. break;
  88. }else{
  89. pop(&pilha);
  90. }
  91. }else if(string[count] == '}'){
  92. if(topoPilha(&pilha) != '{'){
  93. correto = 0;
  94. break;
  95. }else{
  96. pop(&pilha);
  97. }
  98. }else if(string[count] == ']'){
  99. if(topoPilha(&pilha) != '['){
  100. correto = 0;
  101. break;
  102. }else{
  103. pop(&pilha);
  104. }
  105. }
  106. }
  107.  
  108. if(vaziaPilha(&pilha) != 1) correto = 0;
  109.  
  110. if(correto == 1){
  111. printf("Expressão correta.\n");
  112. }else{
  113. printf("Expressão incorreta.\n");
  114. }
  115.  
  116. return 0;
  117. }
Advertisement
Add Comment
Please, Sign In to add comment