美文网首页
从中缀向后缀转换表达式

从中缀向后缀转换表达式

作者: SummerC0ld | 来源:发表于2017-04-06 15:22 被阅读0次

    C实现

    #include "stdio.h"
    #include "string.h"
    #include "stdlib.h"
    typedef struct stack
    {
      char *base;
      char *top;
    } stack;
    int pre(char sign)
    {
      switch (sign)
         
        {
        case '+':
        case '-':
            return 1;
            break;
        case '*':
        case '/':
            return 2;
            break;
        case '^':
            return 3;
            break;
        default:
            return 0;
            break;
           
        }
    }
    int main()
    {
      stack sign;
      int n, i;
      char expre[100];
      scanf("%d", & n);
      while (n--)
         
        {
            sign.base = (char *)malloc(100 * sizeof(char));
            sign.top = sign.base + 1;
            *sign.base = '#';
            scanf("%s", expre);
            for (i = 0; expre[i] != '#'; i++) 
          {
               if (expre[i] == '(') 
            {
                  *sign.top++ = expre[i];
                 
            }
               else if (expre[i] == ')')
            {
                  while (*(sign.top - 1) != '(') 
              {
                     printf("%c", * (sign.top - 1));
                     sign.top--;
                    
              }
                  sign.top--;
                 
            }
               else if (expre[i] == '+' || expre[i] == '-' || expre[i] == '*' || expre[i] == '/' || expre[i] == '^')
            {
                  while (((*(sign.top - 1) == expre[i]) && (expre[i] == '^')) ? (pre(*(sign.top - 1)) > pre(expre[i])) : (pre(*(sign.top - 1)) >= pre(expre[i]))) 
              {
                     printf("%c", * (sign.top - 1));
                     sign.top--;
                    
              }
                  *sign.top++ = expre[i];
                 
            }
               else printf("%c", expre[i]);
              
          }
            while (sign.top != sign.base + 1) 
          {
               printf("%c", * (sign.top - 1));
               sign.top--;
              
          }
            printf("\n");
           
        }
      return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:从中缀向后缀转换表达式

          本文链接:https://www.haomeiwen.com/subject/hbrqattx.html