数据结构(实验三)栈和队列 —— 2.表达式转换

7-2 表达式转换

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。

输入格式:

输入在一行中给出不含空格的中缀表达式,可包含+-*\以及左右括号(),表达式不超过20个字符。

输出格式:

在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。

输入样例:

2+3*(7-4)+8/4

结尾无空行

输出样例:

2 3 7 4 - * + 8 4 / +

结尾无空行

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

void print() //若需要输出空格则输出
{
    static int flag = 0;//static变量存放在静态存储区,只进行一次初始化
    if(flag) putchar(' ');
    flag++;
}

int main()
{
    char str[31];//输入字符串
    char stack[31];//储存运算符号的栈
    int top = -1;//top为-1表示栈空
    int i;
    gets(str);
    int len = strlen(str);
    for(i=0; i<len; i++)
    {
        if((str[i]=='+'||str[i]=='-')&&(!i||str[i-1]=='(')||isdigit(str[i]))
        {
            //数字或正负号直接输出//正负号只能出现在开头或中间的(之后
            print();
            if(str[i]!='+') putchar(str[i]);//正号虽意味着之后的字符直接输出但正号本身不输出
            while(str[i+1]=='.'||isdigit(str[i+1])) putchar(str[++i]);//小数点和数字输出
        }
        else  //处理运算符
        {
            if(str[i]==')') //遇到右括号则将左括号前所有运算符全部输出
            {
                while(top>-1&&stack[top]!='(')
                {
                    print();
                    putchar(stack[top--]);
                }
                if(top>-1) --top;//如果栈不空,跳过左括号
            }
            else  //除右括号外的其他情况
            {
                if(top==-1)
                {
                    stack[++top] = str[i];
                    continue;
                }
                while(top>-1&&stack[top]!='(') //栈顶操作符优先级高时不断输出栈顶操作符,当前优先级高则终止循环
                {
                    if(str[i]=='('||((str[i]=='*'||str[i]=='/')&&(stack[top]=='+'||stack[top]=='-')))
                        break;
                    print();
                    printf("%c",stack[top--]);
                }
                stack[++top] = str[i];//当前操作符入栈
            }
        }
    }
    while(top>-1) //已处理完毕,输出栈中剩余操作符
    {
        print();
        if(stack[top]!='(') putchar(stack[top--]);//除左括号外依次输出
        else top--;//跳过左括号
    }
    return 0;
}

转载:PTA_数据结构与算法_7-20 表达式转换 (25分)_dgyzmyx-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

趟水过河

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值