Help with arithmetic expression using stack

Asked

Viewed 36 times

0

Hello, good morning, everyone! I have a problem solving this exercise, and I don’t really know where to go. My program must have an input that is a mathematical expression and must have as output S or N, which says whether the expression is valid or not in terms of parentheses ( ), brackets [ ] and keys { }. For an expression to be valid, Everything that has been opened has to be closed in the correct order and there should be nothing left at the end. Everything else (numbers, spaces and signals operation) can be ignored. For example, (5+23-[3+1]) is a valid expression, and {32+(4/7}) is an invalid expression. In my code, the program only works if there are no numbers, and when there are always output "N". See:

#include <stdio.h>
#include <string.h>

void *mallocX (unsigned int nbytes) 
{
   void *ptr;
   ptr = malloc (nbytes);
   if (ptr == NULL) {
      printf ("malloc devolveu NULL\n");
      exit (EXIT_FAILURE);
   }
   return ptr;
}
int bemFormada (char s[]){
   char *pilha; int t; 
   int n, i;
   n = strlen (s);
   pilha = mallocX (n * sizeof (char));
   t = 0;
   for (i = 0; s[i] != '\0'; ++i) {
      switch (s[i]) {
         case ')': if (t != 0 && pilha[t-1] == '(') 
                      --t;
                   else return 0;
                   break;
         case ']': if (t != 0 && pilha[t-1] == '[') 
                      --t;
                   else return 0;
                   break;
         case '}': if (t != 0 && pilha[t-1] == '{') 
                      --t;
                   else return 0;
                   break; 
         default:  pilha[t++] = s[i];
      }
   }
   free (pilha);
   if (t == 0) return 1;
   else return 0; 
}

int main (){
   char string[500];
   scanf("%s", string);
   if(bemFormada(string)){
      printf("S");
   }else {
      printf("N");
   }
   return 0;
}

I don’t know how to proceed and make it work with numbers as well. Can anyone help me? I am immensely grateful!

  • You’re stacking operators and digits. Just ignore. Why did you write mallocX that looks exactly like malloc()? Deploy stack(0 in the usual, generic mode, with push() pop(0 and top() and such. It is more readable and more useful in the future

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.