数据结构-中序转后序

#include<iostream>
#include<vector>
#include<string>
#include<cstdio>
#include<cctype>

using namespace std;

void print(vector<string> &);
void transform(vector<string>&,vector<string>&);

int main()
{
    cout<<"请输入阿拉伯数字 ";
    vector<string> _in_vec;
    char tmp;
    string s;
    stringstream stream;
    while((tmp = getchar()) != ' ')
    {
        if(tmp == '+'||tmp=='-'||tmp=='*'||tmp=='/'||tmp=='('||tmp==')')
        {
            if(!s.empty())
            {
                _in_vec.push_back(s);
                s.clear();
            }
            stream<<tmp;
            stream>>s;
            stream.clear();
            _in_vec.push_back(s);
            s.clear();
        }
        else if(tmp == ' ')
        {
            if(!s.empty())
            {
                _in_vec.push_back(s);
                s.clear();
            }
        }
        else if(isdigit(tmp))
        {
            s += tmp;
        }
    }
    if(!s.empty())
    {
        _in_vec.push_back(s);
        s.clear();
    }
    print(_in_vec);
    vector<string> _out_vec;
    transform(_in_vec,_out_vec);
    print(_out_vec);
    
    return 0;
}

void print(vector<string> & _vec)
{
    cout<<" ";
    for(int i = 0 ;i < _vec.size();i++)
        cout<<_vec[i];
}

void transform(vector<string>&_in_vec,vector<string>&_out_vec)
{
    vector<string> tmp;
    for(int i = 0;i != _in_vec.size();i++)
    {
        if(isdigit((_in_vec[i]).at(0)))
            _out_vec.push_back(_in_vec[i]);
        else if(_in_vec[i] == ")")
        {
            while(!tmp.empty() && tmp.back() != "(")
            {
                _out_vec.push_back(tmp.back());
                tmp.pop_back();
            }
            if(!tmp.empty())
                tmp.pop_back();
        }
        else if(_in_vec[i] == "+" || _in_vec[i] == "-")
        {
            if(!tmp.empty() && (tmp.back() == "*" || tmp.back() == "/"))
            {
                _out_vec.push_back(tmp.back());
                tmp.pop_back();
            }
            if(!tmp.empty() && (tmp.back() == "+" || tmp.back() =="-"))
            {
                _out_vec.push_back(tmp.back());
                tmp.pop_back();
            }
            tmp.push_back(_in_vec[i]);
        }
        else if(_in_vec[i] == "*" || _in_vec[i] == "/")
        {
            if(!tmp.empty() && (tmp.back() == "*" || tmp.back() == "/"))
            {
                _out_vec.push_back(tmp.back());
                tmp.pop_back();
            }
            tmp.push_back(_in_vec[i]);
        }
        else
            tmp.push_back(_in_vec[i]);
    }
    while(!tmp.empty())
    {
        _out_vec.push_back(tmp.back());
        tmp.pop_back();
    }
}

原文地址:https://www.cnblogs.com/jkred369/p/4612042.html