7-20 表达式转换 (25分)

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

2 3 7 4 - * + 8 4 / +
当初写的时候死活没考虑到会有小数的情况和运算数前有正负号的情况都快自闭了
看来被人的blog才知道,怪自己脑子惯性思维,做一个合格的程序猿还是要善于找各种bug啊
写的时候左改右改导致代码很难看,,见谅
/*
    Name:
    Copyright:
    Author:  流照君
    Date: 2019/8/13 10:14:26
    Description:
*/
#include <iostream>
#include<string>
#include <algorithm>
#include <vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
stack<char> st;
bool check(char c)
{
    char s=st.top();
    if((c=='-'||c=='+')&&(s=='('))
    return true;
    else if((c=='*'||c=='/')&&(s=='-'||s=='+'||s=='('))
    return true;
    else if(c=='(')
    return true;
    else
    return false;
}
bool check1(char c)
{
    char s=st.top();
    if (s=='*'||s=='/')
    return true;
    else if ((c=='-'||c=='+')&&(s=='-'||s=='+'))
    return true;
    else 
    return false;
}
int main(int argc, char** argv)
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int tag=1,flag=1;
    string s;
    cin>>s;
    int n=s.size();
    for(int i=0;i<n;i++)
    {
        if(!isdigit(s[i]))
         flag=0;
    }
    if(flag==1)
    {
        cout<<s;
        return 0;
    }
    for(int i=0;i<n;i++)
    {
        if(isdigit(s[i])||s[i]=='.')
        {
            while(isdigit(s[i+1])||s[i+1]=='.')
            {
            cout<<s[i];
            i=i+1;
            }
            cout<<s[i]<<" "; 
            tag=0;
        }
        else if((s[i]=='+'||s[i]=='-')&&tag==1&&isdigit(s[i+1])&&i<n-1)
            {
                if(s[i]=='-')
                cout<<s[i];
            }
        else if(st.empty()||check(s[i]))
        {
            st.push(s[i]);
            tag=1; 
        }
        else if(s[i]==')')
        {
            while(st.top()!='(')
            {
                cout<<st.top()<<" ";
                st.pop();
            }
            st.pop();
            //cout<<"eefeff"<<endl;
        }
        else if(check1(s[i]))
        {
            while(check1(s[i]))
            {
                cout<<st.top()<<" ";
                st.pop();
                if(st.empty())
                break;
            }
            st.push(s[i]);
            tag=1;
            //cout<<s[i]<<"www"<<endl;
        }
    }
    if(st.size()==1)
    {
        cout<<st.top();
    }
    else 
    {
        while(!st.empty())
        {
            if(st.size()==1)
            {
            cout<<st.top();
            break;
            }
            else
            {
                cout<<st.top()<<" ";
                st.pop();
            }
        }
    }     
    return 0;
posted @ 2020-02-22 20:07  流照君  阅读(459)  评论(0编辑  收藏  举报