练习3.20 a 将中缀表达式转换为后缀表达式

//将中缀表达式转换为后缀表达式
int
main()
{
    int MaxSize = 10;
    int str[8]={3,3,2,1,0,1,0,2};
    char tmp;
    PtrToStack s;
    s = CreateStack( MaxSize );
    while(1)
    {
        tmp = getchar();
        if(tmp == '
')
            break;
        if(tmp == ' ')
            continue;
        else if(tmp == '+' || tmp == '-' || tmp == '*'
                || tmp == '/' || tmp == '(' || tmp == ')')
        {
            if( IsEmpty( s ) )
                Push( tmp, s );
            else
            {
                if( tmp == ')' )
                {
                    while( Top(s) != '(' )
                    {
                        printf("%c ",Top(s));
                        Pop( s );
                    }
                    Pop( s );
                }
                else
                {
                    while( !IsEmpty(s) && Top(s) != '(' && str[ tmp - '(' ] <= str[ Top(s) - '(' ] )
                    {
                        printf("%c ",Top( s ));
                        Pop( s );
                    }
                    Push( tmp, s );
                }
            }
        }
        else
            printf("%c ",tmp);
    }
    while( !IsEmpty( s ) )
    {
        printf("%c ",Top( s ) );
        Pop( s );
    }
    return 0;
}
View Code

该程序只可以a+b*c等任何式子都可以workout

123+123*321 由于是用getchar()来做的,所以没能做这种式子

 之所以把)单独拿出来,因为他的出现会让一众的符号出栈

b.只需要^添加到数组中去,幂^的优先级比乘除高,比()低

原文地址:https://www.cnblogs.com/gabygoole/p/4643513.html