中缀转前缀


# infix [] -> 中缀表达式 ; s2[] -> 栈的顺序表 ; top2 -> 栈顶指针 ; len表达式长度
void infixToPostFix(char infix[ ], char s2[ ], int &top2, int len)
{
    char s1[maxSize];       #s1辅助栈
    int top1 = -1;
    int i = len-1;
    while(i >= 0)
    {
        if('0' <= infix[i] && infix[i] <= '9')
        {
            s2[++top2] = infix[i];
            --i;
        }
        else if(infix[i] == ')' )
        {
            s1[++top1] = ')';
             --i; 
        }
        else if (infix[i] == '+' || infix[i] == '-' ||
                    infix[i] == '*' || infix[i] == '/')
        {
            if(top1 == -1 || s1[top1] == ')' ||      #当栈为空
                getPriority(infix[i]) >= getPriority(s1[top1]))     #当前优先级 >= 栈顶优先级
            {
                s1[++top1] = infix[i];
                --i;
            }
            else
                s2[++top2] = s1[top1--];      #将运算符入栈到s2中
        }
        else if(infix[i] == '(')      #当遇到左括号
        {
            while(s1[top1] != ')')
                s2[++top2] = s1[top1--];
            --top1;
            --i;
        }
    }
    while(top1 != -1)
        s2[++top2] = s1[top--];
}

posted @ 2021-02-28 10:52  当时不杂  阅读(72)  评论(0编辑  收藏  举报