表达式转换

#include<stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 #include<iostream>
 using namespace std;
stack<char> op;
int flag;
int main(){
    char stack[50];
    char str[50];
    scanf("%s", str);
    int len = strlen(str);
   
    for(int i = 0; i<len; i++){
     
        if((str[i] == '+' || str[i] == '-') && (!i || str[i - 1] == '(') || (str[i] >= '0' && str[i] <= '9')){
            if(!flag){
                flag++;
            }
            else 
                cout<<" ";
            if(str[i] != '+')   putchar(str[i]);
            while(str[i + 1] == '.' || (str[i + 1] >= '0' && str[i + 1] <= '9'))
                putchar(str[++i]);
        }
        else{
            //处理运算符
            if(str[i] == ')'){//遇到右括号,则需要将左括号前的运算符全部弹栈输出
                while(!op.empty() && op.top()!= '('){
                    cout<<" "<<op.top();
                    op.pop();
                }
                //如果栈不为空
                if(!op.empty())  
                op.pop();  //左括号只弹栈,不输出
            }
            else  {
                 if(op.empty()){   //栈为空,无须比较,直接压栈
                op.push(str[i]);
                     continue;
                }
                //根据优先级顺序,压栈||(弹栈后压栈)
                while(!op.empty() && op.top()!= '('){
                    //比较优先级,如果str[i]的优先级大于栈顶运算符的优先级,直接压栈
                    if(str[i] == '(' || ((str[i] == '*' || str[i] == '/') && (op.top() == '-' || op.top() == '+')))
                        break;
                    //如果str[i]的优先级小于栈顶的优先级,弹栈,之后再把str[i]压栈
                   cout<<" "<<op.top();
                   op.pop();
                }
               op.push(str[i]);
            }
            
        }
    }
    while(!op.empty()){ //所有运算数均已操作完毕,最后将栈中剩余的操作符全部输出
        cout<<" "<<op.top();
        //左括号不输出
     op.pop();
    }
    return 0;
}

注意的地方就是 判断栈为空,将符号进栈的过程,其中要判断str[i]是不是’)’ ,如果是的话,有可能此时栈是空的,但是会将’)'进栈,结果出错。
在这里插入图片描述
参考文档:https://blog.csdn.net/op_mocun/article/details/105148288

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值