用栈实现逆波兰式转换 (ReversePolishNotation base on Stack)

问题描述:将由+,-,*,/, (, )和单字母变量组成的普通表达式转换成逆波兰式。
逆波兰式示例:a+b → ab+ 
                        a+b*c   abc*+ 
                        a+b*c-e abc*+e-
PS:输入为'#'是结束标志
代码如下:
#include
#include
#define MAXSIZE 20
typedef struct SeqStack
{
     int data[MAXSIZE];
     int top;
}SeqStack;
SeqStack s;
void ReversePolishNotation()
{
     char input[MAXSIZE], result[MAXSIZE];
     int i = 0, j = 0;
     s.top = -1;
     gets_s(input, MAXSIZE);
     while (input[i] != '#')
     {
          if (input[i] == '(' || input[i] == ')')
          {
               if (input[i] == '(')
                    s.data[++s.top] = input[i];
               else if (input[i] == ')')
               {
                    while (s.data[s.top] != '(')
                         result[j++] = s.data[s.top--];
                    s.top--;
               }
          }
         else if (input[i] <= 'z' && input[i] >= 'a')
              result[j++] = input[i];
         else if ((input[i] == '+') || (input[i] == '-'))
         {
              while (s.top != -1 && s.data[s.top] != '(')
                  result[j++] = s.data[s.top--];
              s.data[++s.top] = input[i];
         }
         else if (input[i] == '*' || input[i] == '/')
         {
              if ((s.top != -1) && s.data[s.top] != '(' && ((s.data[s.top] == '*') || (s.data[s.top] == '/')))
                  result[j++] = s.data[s.top--];
              s.data[++s.top] = input[i];
         }
         i++;
     }
     while (s.top != -1)
         result[j++] = s.data[s.top--];
     result[j] = '\0';
     for (j = 0; result[j]!='\0'; j++)
         printf("%c", result[j]);
     printf("\n");
}
int main()
{
     ReversePolishNotation();
     system("pause");
}
编译环境: Visual Studio


你可能感兴趣的:(Data,Strutures,and,Algorithm)